標籤:
jQuery 1.9/2.0/2.1及其以上版本無法使用live函數了,然而jQuery 1.9及其以上版本提供了on函數來代替。本文講解了jQuery on函數的使用方法,以及在使用jQuery函數中遇到的一些問題。
jQuery on函數文法
1 |
$(selector).on(event,childSelector,data,function,map) |
各個參數說明如下:
| 參數 |
描述 |
| event |
必需。規定要從被選元素移除的一個或多個事件或命名空間。由空格分隔多個事件值。必須是有效事件。 |
| childSelector |
可選。規定只能添加到指定的子項目上的事件處理常式(且不是選取器本身,比如已廢棄的 delegate() 方法)。 |
| data |
可選。規定傳遞到函數的額外資料。 |
| function |
可選。規定當事件發生時啟動並執行函數。 |
| map |
規定事件映射 ({event:function, event:function, …}),包含要添加到元素的一個或多個事件,以及當事件發生時啟動並執行函數。 |
按照上面的文法下面的例子是可以實現的
12345678910111213141516171819 |
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script><script>$(document).ready(function(){ $("p").on("click",function(){ alert("The paragraph was clicked."); });});</script></head><body> <p>Click this paragraph.</p> </body></html> |
但是如果要綁定的on方法是動態載入出來的元素,那麼這樣使用就是沒有用的。看下面的例子:
123456789101112131415161718192021222324252627282930313233 |
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script><script>$(document).ready(function(){ $("#div1").click(function(){ $("<div class=‘test‘>test</div>").appendTo($("#div1")); }); $(".test").on("click",function(){ $(".test").css("background-color","pink"); }); $("#div2").bind("click",function(){ $(this).css("background-color","pink"); });});</script></head><body> <h4 style="color:green;">This example demonstrates how to achieve the same effect using on() and bind().</h4> <div id="div1" style="border:1px solid black;">This is some text.<p>Click to set background color using the <b>on() method</b>.</p></div><br> <div id="div2" style="border:1px solid black;">This is some text.<p>Click to set background color using the <b>bind() method</b>.</p></div> </body></html> |
上面例子中.test元素是動態載入的,但是給它綁定click方法的時候,明明使用了
1 |
$(".test").css("background-color","pink"); |
將背景色設為pink,但是沒有起作用,什麼原因呢,原因就在於.test是動態載入的元素,而使用上面的方法不能綁定動態載入元素的事件,修正的方法為使用下面的代碼代替:
123456789101112131415161718192021222324252627282930313233 |
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script><script>$(document).ready(function(){ $("#div1").click(function(){ $("<div class=‘test‘>test</div>").appendTo($("#div1")); }); $(document).on("click",".test",function(){//修改成這樣的寫法 $(".test").css("background-color","pink"); }); $("#div2").bind("click",function(){ $(this).css("background-color","pink"); });});</script></head><body> <h4 style="color:green;">This example demonstrates how to achieve the same effect using on() and bind().</h4> <div id="div1" style="border:1px solid black;">This is some text.<p>Click to set background color using the <b>on() method</b>.</p></div><br> <div id="div2" style="border:1px solid black;">This is some text.<p>Click to set background color using the <b>bind() method</b>.</p></div> </body></html> |
究其元素就在於使用$(document)意義就在於使元素載入完後才執行方法,所以當為jQuery動態載入的元素繫結on方法的時候,使用$(document)設定代碼指令碼在DOM元素載入完成後開始執行。
jQuery 1.9/2.0/2.1及其以上 on 無效的解決辦法