2012-12-22 162 views
0

爲什麼它運行第二個腳本,我該如何使它像切換控件一樣工作?腳本執行中的意外命令

<script> 
    var el = 2; 

    $(document).ready(function(){ 
     $(".rightDiv").click(function(){ 
      if (el == 2) { 
       $(this).animate({left:'150px'}); 
       el = 1; 
      } 
     }); 
    }); 
</script> 

<script> 

    $(document).ready(function(){ 
     $(".rightDiv").click(function(){ 
      if (el==1) { 
       $(this).animate({left:'50px'}); 
       el = 2; 
      } 
     }); 
    }); 
</script> 
+2

它運行這兩個語句,因爲你已經附加了2個'click'回調函數。查看http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery,瞭解如何在附加新事件之前刪除當前事件處理程序。 – h2ooooooo

回答

0

這應該對你罰款:

var el = false; 
$(document).ready(function() { 
    $(".rightDiv").click(function() { 
     $(this).stop(true).animate({left: (el ? 50 : 150) + 'px'}); 
     el = !el; 
    }); 
});​ 

jsfiddle with example

0

你atteached兩個事件處理程序,所以當事件發生時它會運行一個,那麼其他。

由於第一個將更改變量以使第二個條件成爲true,因此將在兩個if語句內運行代碼。

將代碼放在同一個事件處理程序,讓您可以使用else只運行其中的一個:

<script> 
    $(document).ready(function(){ 

    var el = 2; 

    $(".rightDiv").click(function(){ 
     if (el == 2) { 
     $(this).animate({left:'150px'}); 
     el = 1; 
     } else { 
     $(this).animate({left:'50px'}); 
     el = 2; 
     } 
    }); 

    }); 
</script> 
1

你只需要一個。就緒()

$(document).ready(function() 
{ 
    var el = false; 
    var rightDivs = $('.rightDiv'); 
    $(rightDivs).click(function(){ 
     if (el == false) 
     { 
     $(this).animate({left:'150px'}); 
     el = true; 
     } 
     else if (el == true) 
     { 
     $(this).animate({left:'50px'}); 
     el = false; 
     } 
    }); 
}); 
0

here's一@ h2ooooooo的答案略有改進,我們放棄了全局作用域變量並使用了元素的屬性。

基本上我們在這裏做的是通過使用全局變量來防止膨脹全局範圍,現在我們正在處理與被按下的元素直接相關的數據。

$(document).ready(function() { 
    $(".rightDiv").attr("isLeft",1).click(function() { 
     var pos = "50"; 
     if($(this).attr("isLeft") == "1"){ 
      pos = "150"; 
      $(this).attr("isLeft",0) 
     }else{ 
      $(this).attr("isLeft",1); 
     } 
     $(this).stop(true).animate({left: pos + 'px'}); 
    }); 
}); 
+0

你應該明確地使用'.data()'而不是'.attr()'(此外 - 你不應該設置一個自定義屬性,而不用預先加入data-')。 – h2ooooooo