我有一个玩家数据表,每行旁边都有一个删除按钮。 单击该按钮时,应该使用 jQuery 立即删除该特定行。到目前为止我已经包含了我的代码。当应该单击按钮时我真的被卡住了。我应该使用 header 函数吗?
index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"></link>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<!-- Create a table-->
<table style width="800" border="1" cellpadding="1" cellspacing="1">
<!-- Create headings. Every row is defined as with <tr> tag-->
<!-- Create headings. Every row is defined as with <tr> tag-->
<tr>
<th>Player ID</th>
<th>Player Name</th>
<th>Player Position</th>
<th>Delete</th>
</tr>
<?php
require "php/conn.php";
//Select query
$res = $db -> query ("SELECT * FROM player");
//Set pointer to 1
$res -> data_seek(0);
//Display data using while loop
while ($row = $res -> fetch_assoc()) {
// Write html code in php using this method
echo "<div class = 'row'>";
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['surname']."</td>";
echo "<td>".$row['position']."</td>";
echo "<td><button id = 'dlt_btn' type='button'>Delete</button></td>";
echo "</tr>";
echo "</div>";
}
?>
</body>
script.js
$(document).ready(function () {
$("#dlt_btn").click(function(){
//Activate 'delete.php'
});
});
删除.php
?
最佳答案
在此上下文中,您应该使用类与 ID,但您可以使用 $(this) 来定位单击的元素,并通过 .parent() jquery 方法遍历/删除。这纯粹是为了从 DOM 中删除行,您需要执行 ajax 请求来告诉服务器要从数据库中删除哪一行。在这种情况下,您应该将行 ID 属性添加到 html 中,并将其与 AJAX 请求一起发送。
您可以将行 ID 作为属性附加到按钮中,例如
<button id = 'dlt_btn' type='button' row-id='<?=$yourRowID%>'>Delete</button>
$(document).ready(function () {
$("#dlt_btn").click(function(){
let rowId = $(this).attr('row-id'); //Pull the attribute from your button
let tr = $(this).parent().parent(); //Define the TR itself
$.post('/delete.php', {row_id: rowId}, function(result){
//Do something with the message your page returns after deleting
tr.remove(); //Remove the TR from the dom
});
});
});
关于javascript - 使用 jquery 单击按钮时如何删除特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376349/