javascript - 如何在onclick事件中使用父表的id作为参数?

标签 javascript html html-table

我将为这个页面上的每个表(大约 25 个不同的表)设置一次这个按钮,我希望找到一种方法来调用 onclick 事件函数 constructDataValueString 并传入父表的 id(这样我就不必显式引用表 ID)。

有没有办法这样写:

onclick="constructDataValueString(*id_of_parent_table*)"

HTML 标记的图形示例:

My HTML structure

最佳答案

您可以使用 closest() ,例如:

onclick="constructDataValueString(this.closest('table').id)"

示例

const constructDataValueString = (id) => console.log("table id is: ", id);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:50% !important;}
<table id="populationbyage" border="2">
<thead>TABLE</thead>
<tbody>
  <tr>
    <td>
      Some Cell...
    </td>
    <td>
      <button onclick="constructDataValueString(this.closest('table').id)">
        Copy
      </button>
    </td>
  </tr>
</tbody>
</table>

关于javascript - 如何在onclick事件中使用父表的id作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54319503/

相关文章:

javascript - Firefox 每次刷新都会更改选择单选框!

HTML:时间格式中的字母 T - 有什么用?

javascript - 防止页面在后退按钮上重新加载(使用缓存)。或者向下滚动用户。 (问题,至少,iPhone)

javascript - 为什么在我向其中添加更多项目后 node.js 以不同方式呈现数组?

html - Firefox 和 Chrome 中未触发表 onkeyup 事件

html - 如何使 <td> 作为链接可点击(无需 Javascript)

javascript - 如何在不对特定行进行排序的情况下使 html 表可排序?

html - 使用 HTML 嵌套表格

JavaScript:ActiveX 对象和 apply() 函数的问题

javascript - 在缩略图悬停时显示图像下拉列表,悬停时隐藏它