我试图在点击 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/