使用Jquery解决:动态生成的元素无法绑定事件
概况
在实际的html页面开发中,很多时候,我们的页面样式不是预先定义的,例如:分页按钮的生成、数据的显示等等,这些数据都是当我们的服务器启动后,客户端浏览器跳到指定页面,然后通过servlet等与数据库进行数据交互,然后动态的生成的表格、按钮等等,往往这些生成的元素还会附带一些交互功能,例如:在表格中生成的一行数据,最后的按钮具有删除这一行的功能,本小结就是为了解决动态生成的元素具有事件效应。
- 编写html测试
<html><head><meta charset="utf-8"><title></title></head><script src="jquery/jquery-3.6.0.min.js"></script><script>$(function(){ $("#add").click(function(e){// 动态创建行$("#table").append(" ")})$("input[title='del']").click(function(){//删除该事件的父亲节点,是tr类型$(this).parents('tr').remove();})})</script><body><div><table id="table"><tr id="pre"><th><input type="checkbox" /></th><th>姓名</th><th>性别</th><th><input type="button" value="增加按钮" id="add"/></th></tr><tr><td><input type="checkbox" /></td><td><input type="file" /></td><td><input type="radio" /></td><td><input type="button" value="删除按钮" title="del"/></tr></table></div></body></html>
扩展解释:
$(this).parent().parent().remove();
//层层寻找父亲节点元素
$(this).parents('tr').remove();
//找到其所有的父亲节点(祖父)类型为tr
$(this).parents('tr').find(".del").remove();
//找到其所有的父亲节点(祖父)类型为tr并且其class为del
效果1:
小结:
发现此方法并不可行,动态生成的元素,无法绑定事件
修改:
<script>$(function(){ // $("input[title='del']").click(function(){// //删除该事件的父亲节点,是tr类型// $(this).parents('tr').remove();// })$("#table").on("click","input[title='del']",function(){$(this).parents('tr').remove();})})</script>
效果2: