一、錯誤示例:
對於自己用腳本動態生成的元素,無法綁定事件。例如:
body下的代碼:
<body> <ul> <li><span class="class1">11111</span></li> <li><span class="class1">22222</span></li> <li><span class="class1">33333</span></li> </ul> <script src="../static/js/jquery.min.js"></script> <script> aButton=$('li') aButton.each(function(i){ aButton.eq(i).attr('tag','edit') $(this).click(function(){ $(this).html('<a href="#" class="active">'+i+'</a>') }) }) aA=$('a') aA.each(function(i){ console.log('kkkk') $(this).click(function(){ console.log('i') }) }) </script> </body>
運行結果:
當span標籤被點擊的時候,變成a標籤,然後再點擊a標籤,沒有任何反應。
原因:結果當生成a標籤之後,無論如何點擊都沒有效果,因爲jquery只能綁定頁面本身存在的元素。動態生成的元素不能被綁定。而click事件,其實是bind('click',...)的簡化形式。
二、正確的方法:
<body> <ul> <li><span class="class1">11111</span></li> <li><span class="class1">22222</span></li> <li><span class="class1">33333</span></li> </ul> <script src="../static/js/jquery.min.js"></script> <script> aButton=$('li') aButton.each(function(i){ aButton.eq(i).attr('tag','edit') $(this).click(function(){ $(this).html('<a href="#" class="active">'+i+'</a>') }) }) $('li').delegate('a[class=active]','click',function(){ //獲取當前動態創建元素的索引值: iNow=$('a[class=active]').index(this) console.log('iNow:',iNow) console.log($(this).html()) }) </script> </body>
運行結果:
當span標籤被點擊的時候,變成a標籤,然後再點擊a標籤,console裏打印出它的html內容並且打印新創建元素中被點擊的索引。
iNow:0
0
iNow:1
2
結果截圖如下
說明:
1)delegate方法,代理或者說是委託,實現原理是事件的冒泡,在指定的祖先元素中註冊事件(delegate在特定元素上),元素事件觸發,傳播到這個元素然後進行篩選。可以在祖先元素中綁定事件,比如上面的li是祖先元素,而新生成的元素a都是li的子元素,所以動態生成的元素的事件就可以綁定了。
delegate官網介紹:Attach a handler to one or more events for all elements that match the selector,now or in the future, based on a specific set of root elements.
官網網址:http://api.jquery.com/delegate/
2)選擇器,注意:
var a= $("input:[name^='a']");
表示所有name以a開頭的input。而上面示例a[class=active],表示選中所有class爲active的a標籤