gpt4 book ai didi

javascript - 单击 td 函数时获取表的 ID

转载 作者:行者123 更新时间:2023-11-28 03:21:49 25 4
gpt4 key购买 nike

当单击tabletd时,我试图获取表的id。我的代码如下所示:

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<table id="table_1">
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr>
<td onclick="editUnit()">John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</tbody>
</table>
<script>
function editUnit() {
let tableId = $(this).closest('table').attr('id');
alert(tableId);
}
</script>

我也尝试过 $(this).parents('table').attr('id'); ,但是,仍然是 undefined 的相同结果.

jsfiddle

最佳答案

您的问题是在 HTML 上内联分配监听器,当调用该函数时,this上下文未指向 td ,这就是你未定义的原因。

因此,您至少有两个选择:

  • “不太好”选项:将其传递给监听器并作为函数的参数获取,如下所示:

function editUnit(td) {
let tableId = $(td).closest('table').attr('id');
console.log(tableId);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<table id="table_1">
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr>
<td onclick="editUnit(this)">John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</tbody>
</table>

  • “更好”选项:分配 id (甚至是一个类)到 <td>并将监听器绑定(bind)到脚本部分,而不是 HTML,这样 this上下文将是正确的,如下所示:

document.getElementById("clickableTd").onclick = editUnit;

function editUnit() {
let tableId = $(this).closest('table').attr('id');
console.log(tableId);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<table id="table_1">
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr>
<td id="clickableTd">John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</tbody>
</table>

关于javascript - 单击 td 函数时获取表的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com