今天在使用jQuery過程中碰到了這個隱藏在代碼中的問題:事件綁定會累加而不會覆蓋掉前者。特此記錄下解決方案。
測試代碼:
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
- <!--[if lt IE 9]>
- <script src="js/html5shiv.js"></script>
- <![endif]-->
- <script src="js/jquery-1.7.2.min.js"></script>
- <script>
- var test = function(){
- $("p").on("click",function(){
- //alert($(this).text());
- console.log($(this).text());
- });
- }
- var ok = function(){
- $("p").off().on("click",function(){
- //alert($(this).text());
- console.log($(this).text());
- });
- }
- $(document).ready(function(){
- $("a").click(test);
- $("button").click(test);
- $("input").click(ok);
- });
- </script>
- </head>
- <body>
- <a href="#">第一次</a> <button>第二次</button> <input type="button" value="最終" />
- <p>0</p>
- <p>1</p>
- <p>2</p>
- <p>3</p>
- <p>4</p>
- <p>5</p>
- </body>
- </body>
- </html>
- 看出問題來了嗎?沒看出來那就先後點擊按鈕對數字進行事件綁定,然後再點數字看下效果就知道了。jQuery事件綁定是會累加的,最終那個纔是正確寫法,綁定前先釋放掉。 注:.on及.off在jQuery1.7+支持!