javascript - 使用 jQuery 单击 TR 时检索相应的 TH 值

标签 javascript jquery jquery-ui

我试图在点击 TR 时获取相应 TD 索引的 TH 值。所以在下表中:

<table>
 <thead>
  <th>dogs</th>
  <th>cats</th>
  <th>lizards</th>
 </thead>
 <tbody>
  <tr>
   <td>1</td>
   <td>2</td>
   <td>3</td>
  </tr>
 </tbody>
</table>

使用以下 js:

$("tr").live("click", function() {
    //get values of row headers
    alert( $(this).closest('table').find('th').eq($(this).index()).val() );
 });

当您点击单元格 1 时会提醒“狗”,点击单元格 2 时会提醒“猫”,等等。

目前我的代码只是提醒一个空白的提醒框(什么都没有),但也不会引发任何错误。

想法?

最佳答案

你不想.val() .你要.text()相反。

编辑: 根据评论,因为您仍然希望它通过绑定(bind)到 <tr> 来工作,最终代码应如下所示:

$("tr").live("click", function(event) {
    //get values of row headers
    alert($(this).closest('table').find('th').eq($(event.target).index()).text());
});

注意 event 的传递对象到处理程序,然后使用 event.target 引用实际被点击的元素。

演示 here .

关于javascript - 使用 jQuery 单击 TR 时检索相应的 TH 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8160603/

相关文章:

javascript - 匹配下划线、星号和波形符之间的字符串的正则表达式

jquery - 如何在div集合中获取特定的背景div

jquery - 在我的链接函数中注册的事件监听器未被触发

javascript - 奇怪的CSS位置问题

jquery - 我可以防止 float div 在调整大小时换行吗?

jquery - ng :areq Argument is not a function, 在 AngularJS 中未定义

javascript - 如何知道哪些 JavaScript 函数绑定(bind)到 HTML 元素?

javascript - 用于 JSUnit 测试的公共(public)测试群?

javascript - 使用 Redux 和 React 按顺序执行异步操作

jquery-ui - 如何使 jQuery UI 工具提示在悬停时保持打开状态