
本文旨在解决在动态生成的 HTML 表格中,通过点击按钮获取特定行 RecId 并将其发送到服务器的问题。通过 jQuery 事件委托和 DOM 遍历,我们可以准确地获取到目标 RecId,并使用 AJAX 将其传递给服务器端的 PHP 脚本。本文将详细介绍如何实现这一功能,并提供代码示例和注意事项。
在动态生成的表格中,为每个行都使用相同的 ID 是一个常见的问题。因为 ID 在 HTML 文档中必须是唯一的。 当使用$('#recid').text()时,jQuery 选择器只会返回第一个匹配的元素,导致所有行都获取到第一个 recid 的值。 解决此问题的关键在于使用正确的 DOM 遍历方法,从点击的按钮开始,找到其所在的行,然后从该行中找到对应的 recid 元素。
以下是解决此问题的步骤和代码示例:
由于 ID 应该在 HTML 文档中是唯一的,因此应该将 recid 的 ID 修改为 class。
<tr class="ordertr table-bordered">
<td class="recid d-none"><?=$row['RecId']?></td>
<td class="ps-lg-3">
<ul>
<li><button id="editingST">✎</button></li>
<li><button class="towork">?</button></li>
</ul>
</td>
</tr>使用 jQuery 的 closest() 和 find() 方法来定位到正确的 recid 元素。
$("#position-order tbody").on('click', '.towork', function gotowork(e){
const recid = $(e.target).closest('tr').find('.recid').text();
$.ajax({
type: "POST",
url: '/towork.php',
data: {recid: recid}
});
return false;
});代码解释:
在服务器端的 PHP 脚本中,接收并处理传递过来的 recid 值。
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$recid = $_POST['recid'];
// 在这里使用 $recid 进行数据库操作或其他处理
echo "Received RecId: " . $recid;
} else {
echo "Invalid Request";
}
?>HTML:
<table id="position-order">
<tbody>
<tr class="ordertr table-bordered">
<td class="recid d-none">123</td>
<td class="ps-lg-3">
<ul>
<li><button id="editingST">✎</button></li>
<li><button class="towork">?</button></li>
</ul>
</td>
</tr>
<tr class="ordertr table-bordered">
<td class="recid d-none">456</td>
<td class="ps-lg-3">
<ul>
<li><button id="editingST">✎</button></li>
<li><button class="towork">?</button></li>
</ul>
</td>
</tr>
</tbody>
</table>JavaScript:
$(document).ready(function() {
$("#position-order tbody").on('click', '.towork', function gotowork(e){
const recid = $(e.target).closest('tr').find('.recid').text();
$.ajax({
type: "POST",
url: '/towork.php',
data: {recid: recid},
success: function(response) {
console.log(response); // 在控制台显示来自服务器的响应
}
});
return false;
});
});通过使用 jQuery 的 closest() 和 find() 方法,我们可以轻松地在动态生成的表格行中获取到特定的数据。 记住,ID 在 HTML 文档中必须是唯一的,因此应该使用 class 来代替 ID。 此外,为了提高代码的可维护性和可读性,建议将代码封装成函数,并添加适当的注释。
以上就是如何在动态生成的表格行中获取特定字符串并发送到服务器的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号