1. 程式人生 > >jQuery動態新增的元素繫結事件

jQuery動態新增的元素繫結事件

 
今天在做專案是時候發現動態新增的元素不能繫結事件,由於本人js和jquery技術有限,所以也不知道原因,一查才知道,動態新增的元素繫結事件就會失效,所以修改了一下。

jquery中繫結事件一般使用bind,或者click,但是這隻能是對已經載入好的元素定義事件,那些後來新增插入的元素則需要另行繫結。在1.7版本以前使用live。但是在1.8版本以後推薦使用on。
 **定義和用法**  on() 方法在被選元素及子元素上新增一個或多個事件處理程式。
自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。該方法給 API 帶來很多便利,我們推薦使用該方法,它簡化了 jQuery 程式碼庫。
注意:使用 on() 方法新增的事件處理程式適用於當前及未來的元素(比如由指令碼建立的新元素)。 提示:如需移除事件處理程式,請使用 off() 方法。 提示:如需新增只執行一次的事件然後移除,請使用 one() 方法。 <!DOCTYPE html> <html> <head> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("div").on("click","p",function(){
$(this).slideToggle(); }); $("button").click(function(){ $("<p>This is a new paragraph.</p>").insertAfter("button"); }); }); </script> </head> <body> <div style="background-color:yellow"> <p>This is a paragraph.</p> <p>Click any p element to make it disappear. Including this one.</
p
>
<button>Insert a new p element after this button</button> </div> </body> </html>