添加节点之前如图:
点击图中的 "第一个" 之后会触发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动态添加的节点事件无法触发
原文地址:http://www.cnblogs.com/GoneLW/p/7450768.html