Erm,只是这里的一名学生,我要问的问题可能已经在某个地方被问过,但是,我只是不知道我在寻找什么,如果已经被问过,请耐心等待 D : , 无论如何,
-数据来自表格
-我使用了一段js代码,将表格的一行信息放入文本框中进行编辑
-据说最好的做法是不在表中显示主键
-我尝试执行 td style="visibility:hidden"或 display:none 但它弄乱了表格设计,我不知道如何修复它(我尝试过)
-所以是的,主键不包含在显示的行中,我需要更新查询的主键
-我正在考虑将其传递到表单上的 input type="hidden" 中,但由于 js 需要该值位于该行上,因此我需要在表中包含主键,这是我试图避免的。
有什么替代方案或我可以做的事情吗? 我在这方面的经验非常有限,因此可能还有其他替代方案来解决这个问题,但我还不太理解它们。
$(document).ready(function(){
$("#edit-button").click(function(){
var Firstname = $(this).closest("tr").find("td:eq(0)").text();
var Lastname = $(this).closest("tr").find("td:eq(1)").text();
$("#firstname-edit").val(Firstname);
$("#lastname-edit").val(Lastname);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1px">
<thead>
<th>firstname</th>
<th>lastname</th>
<th>action</th>
</thead>
<tbody>
<?php
include "con.php";
$getinfo = mysqli_query($con, "SELECT * FROM usertable")
while($res = mysqli_fetch_array($getinfo ))
{
$id = $res['id'];
$fname = $res['fname'];
$lname = $res['lname'];
echo "<tr>
<td>".$fname."</td>
<td>".$lname."</td>
<td><a href="#" id="edit-button">Edit</a></td>
</tr>";
}
?>
</tbody>
</table>
<form>
<input type="text" id="firstname-edit" placeholder="firstname..."><br>
<input type="text" id="lastname-edit" placeholder="lastname..."><br>
<input type="submit" id="edit-save" name="submit" value="Save">
</form>
最佳答案
我不明白为什么你应该隐藏主 ID,每个有兴趣修改数据库的人都知道大多数表都是这样设计的。
此外,您的编辑按钮具有以下 id:edit-button
,请确保每当您处理多个结果时,每个元素都有一个唯一的 id。
您的脚本现在尝试做的是选择一个最接近 id 的元素; edit-button
其中可能有 20 个。
您最好根据按钮的类选择 .click 事件。
将按钮代码替换为:
<td><a href="#" class="edit-button">Edit</a></td>
并将 JavaScript 行:$("#edit-button").click(function(){
替换为以下内容:
$(document).on('click','.edit-button',function() {
确保脚本选择适当的最接近的名字和姓氏。
关于javascript - 使用 $(this).closest ("tr").find ("td:eq(0)").text() 将值传递给 javascript,但 ID 不包含在表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44591244/