最近在做一个小练习,用ajax实现php后台与html分离,书写过程中遇到给删除按钮增加确认框的同时,遇到点击事件的传递问题,这里记录小技巧,声明一个全局变量或在点击事件中,声明变量记录所点击元素的id,用于删除模块的删除操作。
// 技巧之->声明变量用于存储点击的所属id,用于给,相关模块使用
var userid = 0;
// 为删除按钮注册单击事件
$("tbody").on("click", ".del", function() {
$("#del_modal").css("display", "block");
// 获取当前单击的删除按钮的自定义属性 data-id 的值
userid = $(this).data("id");
});
// 删除数据
$("#btn_del").on("click", function() {
// 发送ajax请求,将用户id传递到服务端
$.ajax({
url: "delUser.php",
type: "get",
data: { id: userid },
dataType: "json",
success: function(res) {
if (res.msg == "ok") {
// 重新加载数据
getUsers();
$("#del_modal").css("display", "none");
}
}
});
});
小案例代码附上:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script src="js/function.js"></script>
<script src="js/index.js"></script>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div class="container">
<h1 class="h1 text-center">学生信息表</h1>
<a href="javascript:;" class="btn btn-default addInfo">增加信息</a>
<a href="javascript:;" class="btn btn-danger multiple_btn">批量删除</a>
<div class="box">
<table class="table table-bordered text-center stuInfo">
<thead>
<th><input type="checkbox" class="multiple_choice"></th>
<th>用户编号</th>
<th>用户名</th>
<th>密码</th>
<th>姓名</th>
<th>手机号</th>
<th>头像</th>
<th>操作</th>
</thead>
<tbody>
</tbody>
</table>
</div>
<!-- 添加数据-->
<div class="addBox">
<h3 class="text-center">增加信息</h3>
<form >
<ul>
<li>用户名<input type="text" class="use