jQuery添加元素后不执行原有事件的方法

我们先来看下我的错误代码

html:

        <table border="1" id="best">
			<tr>
				<td>
					<button class="change">修改</button>
				</td>				
			</tr>
			<tr>
				<td>
					<button class="del">删除</button>
				</td>				
			</tr>
			<tr class="last"><td><button class="add">添加</button></td></tr>
		</table>

js:

$(".add").click(function(){
		var newYuansu = $("<tr><td><button class='del'>删除</button></td></tr>");
		$(".last").before(newYuansu);
})
$(".del").click(function(){
        $(this).parents("tr").remove();
})

而此时使用jQuery新加元素,新元素元素不会执行一部分原有的事件函数

博主是学生,也只是研究了一种方法:

$("#best").on("click",".del",function(){
		$(this).parents("tr").remove();
})

把原本的click事件这样写,就可在新加的元素使用,非常好用~

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>