jQuery事件重複綁定解決方案

 今天在使用jQuery過程中碰到了這個隱藏在代碼中的問題:事件綁定會累加而不會覆蓋掉前者。特此記錄下解決方案。

測試代碼:

  1. <!DOCTYPE HTML> 
  2. <html> 
  3. <head> 
  4. <meta charset="UTF-8" /> 
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  6. <meta name="description" content=""> 
  7. <meta name="author" content=""> 
  8. <!--[if lt IE 9]> 
  9.     <script src="js/html5shiv.js"></script> 
  10. <![endif]--> 
  11. <script src="js/jquery-1.7.2.min.js"></script>    
  12. <script> 
  13.     var test = function(){ 
  14.         $("p").on("click",function(){ 
  15.             //alert($(this).text()); 
  16.             console.log($(this).text()); 
  17.         });      
  18.     } 
  19.      
  20.     var ok = function(){ 
  21.         $("p").off().on("click",function(){ 
  22.             //alert($(this).text()); 
  23.             console.log($(this).text()); 
  24.         });  
  25.     } 
  26.      
  27.     $(document).ready(function(){ 
  28.         $("a").click(test); 
  29.         $("button").click(test); 
  30.         $("input").click(ok); 
  31.     });       
  32. </script>   
  33. </head> 
  34. <body> 
  35.     <a href="#">第一次</a> <button>第二次</button> <input type="button" value="最終" /> 
  36.     <p>0</p> 
  37.     <p>1</p> 
  38.     <p>2</p> 
  39.     <p>3</p> 
  40.     <p>4</p> 
  41.     <p>5</p> 
  42. </body>      
  43. </body> 
  44. </html>
  45.  
  46. 看出問題來了嗎?沒看出來那就先後點擊按鈕對數字進行事件綁定,然後再點數字看下效果就知道了。jQuery事件綁定是會累加的,最終那個纔是正確寫法,綁定前先釋放掉。 注:.on及.off在jQuery1.7+支持! 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章