JQuery动态生成的按钮无法触发问题与解决方法

JQuery动态生成的按钮无法触发问题与解决方法

起因:

利用JQuery动态添加的按钮无法通过$(selector).click方法触发点击事件

//在网页加载完成后动态添加表格
$(function () {
 //通过Ajax向后台请求程序
 $.ajax({
 method : "post",
 url : "all-user",
 dataType : "json",
 success: function (data) {
 const userList = data;
	//遍历结果集
 for (let i = 0; i < userList.length; i++){
 let uid = userList[i].uid
 let upd = '<button value="'+uid+'" class="upd-btn">修改</button>'
 let del = '<button value="'+uid+'" class="del-btn">删除</button>'
 let status = ""
 if (userList[i].status == 0){
 status = "审核中"
 }else if (userList[i].status == 1){
 status = "审核通过"
 }else if (userList[i].status == 2){
 status = "审核被拒绝"
 }
	//添加模板
 let td = "<tr>"+
 "<td>#{uid}</td>"+
 "<td>#{username}</td>"+
 "<td>#{password}</td>"+
 "<td>#{status}</td>"+
 "<td>#{update}</td>"+
 "<td>#{delete}</td>"+
 "</tr>"
	//填充参数
 td = td.replace(/#{uid}/g,uid)
 td = td.replace(/#{username}/g,userList[i].username)
 td = td.replace(/#{password}/g,userList[i].password)
 td = td.replace(/#{status}/g, status)
 td = td.replace(/#{update}/g, upd)
 td = td.replace(/#{delete}/g, del)
 //.append追加
 $("#tb").append(td)
 }
 }
 })
 //编写按钮的点击事件,使用.click()方法,按钮点击后没有反应
 $(".del-btn").click(function () {
	 alert(this.value)
 })
 })

原因:

append中的节点是在整个文档加载完之后开始添加的,
因此页面不会为append的元素初始化添加点击事件

解决方法:

使用$(document).on()方法添加点击事件

$(document).on("click",".del-btn",function (){
 
 })
作者:saffeer原文地址:https://www.cnblogs.com/saffeer/p/17078081.html

%s 个评论

要回复文章请先登录注册