標籤:https col UI 添加 com 父類 cli 解決 無法
添加節點之前
點擊圖中的 "第一個" 之後會觸發click事件,效果
點擊按鈕的之後,添加節點之後
這時點擊圖中的 "第一個",卻不會觸發click事件。
此時代碼如下:
<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><html><head><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script> $(function(){ $(".a1").on("click",function(){ alert("觸發a標籤的點擊事件!"); }); }); function cl(){ $(".div2").html(‘<a class="a1">第一個</a><br><a class="a2">第二個</a>‘); }</script></head><body> <div class="div1"> <div class="div2"> <a class="a1">第一個</a> </div> <input onclick="cl()" type="button" value="添加節點"/> </div></body></html>
以上問題可以通過綁定幾種方法解決
1.是直接在添加標籤的時候添加一個onclick事件;
2.通過綁定這個標籤的父類或者body來達到啟用click事件的效果。
改過之後的代碼如下:
<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><html><head><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script> $(function(){ /*$(".a1").on("click",function(){ alert("觸發a標籤的點擊事件!"); });*/ /*$(".div1").on("click",".a1",function(){ alert("觸發a標籤的點擊事件!"); });*/ $(".div2").on("click",".a1",function(){ alert("觸發a標籤的點擊事件!"); }); /*$("body").on("click",".a1",function(){ alert("觸發a標籤的點擊事件!"); });*/ }); function cl(){ $(".div2").html(‘<a class="a1">第一個</a><br><a class="a2">第二個</a>‘); }</script></head><body> <div class="div1"> <div class="div2"> <a class="a1">第一個</a> </div> <input onclick="cl()" type="button" value="添加節點"/> </div></body></html>
如果出現,點擊一次,出現兩次click事件的話,
考慮使用propagation()方法處理冒泡。
jQuery動態添加的節時間點事件無法觸發