为何DIV元素重建后无法触发绑定的点击函数?
问题描述
我有一组嵌套DIV元素:#grandparent、#parent、#child。点击#child时,#books会被清空,#book容器会添加#new元素;点击#book时,#book会被清空,#books会重新添加#grandparent、#parent、#child这组嵌套元素。
问题是:这些元素被重建后,新生成的#child无法再触发点击事件,没法重复执行上述流程。请问这是什么原因?如何实现循环触发,让#child和#book能持续执行对应函数?
原因分析
- 你当前使用的直接事件绑定(比如
$("#child").click(...))仅对页面初始化时已存在的DOM元素生效。 - 当你通过
html('')删除原有元素并重建新的#child后,新元素并未绑定之前的点击事件处理逻辑,因此点击无响应。
解决方案
采用jQuery的事件委托机制:将事件绑定到页面中始终存在的父级元素(如document、.wrapper),借助事件冒泡特性处理动态生成元素的点击事件。无论元素被重建多少次,只要匹配选择器,就能触发对应逻辑。
修改后的完整代码如下:
CSS 代码
body, div { display: flex; justify-content: center; align-items: center; } .wrapper { left: 50px; width: 100%; height: 300px; } .grandparent { width: 200px; Height: 200px; background-color: red; font-size: 30px; text-align: center; color: white; -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ cursor: pointer; } .parent { width: 130px; Height: 130px; background-color: blue; font-size: 30px; text-align: center; color: white; -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ cursor: pointer; } .child { width: 60px; Height: 60px; background-color: green; font-size: 30px; text-align: center; color: white; -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ cursor: pointer; } .new { width: 200px; Height: 200px; background-color: purple; font-size: 30px; text-align: center; color: white; -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ cursor: pointer; }
HTML & JS 代码
<!DOCTYPE html> <html lang="en"> <head> <title>Touchy!</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> <body> <br> <br> <div class="wrapper"> <div id="books" class="books" > <div id="grandparent" class="grandparent"> <div id="parent" class="parent"> <div id="child" class="child" >07</div> </div> </div> </div> <div id="book" class="book" ></div> </div> <script> $(document).ready(function() { // 用事件委托绑定#child的点击事件,兼容动态生成的元素 $(document).on("click", "#child", function() { $("#books").html(''); $("#book").append("<div id='new' class='new'>12</div>"); console.log("child clicked"); }); // #book是静态元素,直接绑定点击事件即可 $("#book").click(function() { $("#book").html(''); $("#books").append("<div id='grandparent' class='grandparent'>"); $("#grandparent").append("<div id='parent' class='parent'>"); $("#parent").append("<div id='child' class='child'>07</div>"); console.log("new clicked"); }); }); </script> </body> </html>
补充说明
- 事件委托的核心是将监听逻辑放在静态父元素上,当子元素触发事件时,事件会冒泡到父元素,父元素再根据选择器匹配目标元素执行逻辑。
- 如果需要监听
#book内部动态生成的#new元素,同样可以用事件委托:$(document).on("click", "#new", function(){...})。
内容的提问来源于stack exchange,提问作者MarkC
相关产品推荐
相关产品推荐

