2016-05-12 27 views
-1

我有一個顏色選擇器,在拖動時,它會連續調用函數hello(e,2)。我傳遞第二個變量2,以便第一個if statement不會執行。現在,不斷變化,我不想要這個。剛剛得到一個循環的最後一個值,並執行停止功能

list[2] =list[1]; 
list[1]=list[0]; 
list[0]=e; 

這應該只執行最後一次。所以這些地方只是移動一次。我希望你能理解我的問題。這是我的功能。

function hello(e, a) { 
    if (a == 1 && e != list[0] && e != list[1]) { 
     list[2] = list[1]; 
     list[1] = list[0]; 
     list[0] = e; 

     var strContent = ""; 
     for (var i = 0; i <= 2; i++) { 
      strContent += "<div class=\"pick\" style=\"background-color:" + list[i] + "\" onclick=\"hello(this.style.backgroundColor,0);\"></div>"; 
     } 
    } 
    if (a == 2 && e != list[0] && e != list[1]) { 
     list[0] = e; 

     var strContent = ""; 
     for (var i = 0; i <= 2; i++) { 
      strContent += "<div class=\"pick\" style=\"background-color:" + list[i] + "\" onclick=\"hello(this.style.backgroundColor,0);\"></div>"; 
     } 
    } 

    $('#colorpick').html(strContent); 

    //clr = 'rgb('+r+','+g+','+b+')'; 
    clr = e; 
    var rgb = clr.replace(/^(rgb|rgba)\(/, '').replace(/\)$/, '').replace(/\s/g, '').split(','); 
    myColor.r = parseInt(rgb[0]); 
    myColor.g = parseInt(rgb[1]); 
    myColor.b = parseInt(rgb[2]); 
    curColor = myColor; 

    document.getElementById('color-lib-1').style.display = "none"; 
    document.getElementById('color-lib-2').style.display = "none"; 
    document.getElementById('color-lib-3').style.display = "none"; 
    document.getElementById('color-lib-4').style.display = "none"; 

} 
+0

這是不可讀的。請正確縮進您的代碼。 – Tomalak

+1

_I希望你明白我的問題。我三次讀了它,但不能。 – Satpal

+0

所以你說你不想在上次打電話時將「2」作爲「a」的值傳遞給它?我認爲這超出了您向我們展示的功能的控制範圍。函數本身並不知道這是你第一次叫它還是第一百萬。 – ADyson

回答

0

這真的很難猜測你正在嘗試做的有,主要是因爲我相信它可能以更好的方式已經完成。

function hello(e) { 
    if(e === list[0] && e === list[1]){ 
     return false; 
    }else{ 
     list.unshift(e); 
    } 

    var strContent = ""; 
    for (var i = 0; i <= 2; i++) { 
     strContent += "<div class=\"pick\" style=\"background-color:" + list[i] + "\" onclick=\"hello(this.style.backgroundColor,0);\"></div>"; 
    } 

    //followed by whatever code 
} 

它對我來說似乎更清潔,應該爲您的目的服務。雖然不確定!

相關問題