使用Jquery解决:动态生成的元素无法绑定事件

概况

在实际的html页面开发中,很多时候,我们的页面样式不是预先定义的,例如:分页按钮的生成、数据的显示等等,这些数据都是当我们的服务器启动后,客户端浏览器跳到指定页面,然后通过servlet等与数据库进行数据交互,然后动态的生成的表格、按钮等等,往往这些生成的元素还会附带一些交互功能,例如:在表格中生成的一行数据,最后的按钮具有删除这一行的功能,本小结就是为了解决动态生成的元素具有事件效应。

  1. 编写html测试
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<!--引入jquery-->
	<script src="jquery/jquery-3.6.0.min.js"></script>
	<script>
		
		$(function(){ 
			
			$("#add").click(function(e){
				// 动态创建行
				$("#table").append("<tr><td><input type='checkbox' /></td><td><input type='file' /></td><td><input type='radio' /></td><td><input type='button' value='删除按钮' title='del'/></td></tr>")
			})


			$("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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈行恩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值