今天遇到了这个坑花了几个小时,给动态生成的按钮添加单击事件没有响应,参考这位大神的答案,完美解决了
https://blog.csdn.net/u013134432/article/details/85785356?utm_source=app
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.js"></script>
<style>
.deleteBtn{
width: 100%;
}
</style>
</head>
<body>
<button id="selectBtn">查询数据</button>
<button id="addBtn">添加数据</button>
<input type="text" id="username" placeholder="用户名">
<input type="password" id="password" placeholder="密码">
<table border="1" width="500px" class="root" cellpadding="0" cellspacing="0"></table>
<script>
$("#selectBtn").click(function (event) {
//$("li").remove();
$.ajax({
type:"get",
url:"http://localhost:3000/all",
success:function (data) {
$(data).each(function (index,item) {
$(".root").append("<tr><td>"+item.id+"</td><td>"+item.username+"</td><td>"+item.password+"</td><td><button class='deleteBtn' value='"+item.id+"'>删除</button></td><td><button class='deleteBtn' >修改</button></td></tr>")
})
}
})
})
/* 刚开始使用这段代码,单击都没反应
$('.deleteBtn').click(function (event) {
console.log($(this).val());
console.log($(this).attr("value"));
})*/
//使用这段代码就好啦
$(document).on('click','.deleteBtn',function (e) {
console.log($(this).val());
console.log($(this).attr("value"));
});
</script>
</body>
</html>
正常显示的效果