2016-05-12 22 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 
} 

它对我来说似乎更清洁,应该为您的目的服务。虽然不确定!