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

标签 javascript jquery html

当单击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/

相关文章:

javascript - 无法使用使用 Electron JS 的桌面应用程序创建新文件夹

javascript - 暂时停用.hover

html - Angular 8 : Send Form data as a Service to Another Component

javascript - VueJS如何做这种 "for"循环: for(i = 0; i < x; i++)

javascript - 更好的方法来处理 JavaScript 类中的状态变化

javascript - Jquery 获取系列中最后一个元素中表的最后一行

javascript - 折叠表格适用于页面上的所有表格

php - mysql_query如何与一个 "dynamic"数据库一起使用呢?

javascript - 使用ajax动态更改显示的数据

javascript - 如何根据 bool 值在 AngularJS 中切换 ng-show?