[英]How can I get the corresponding table column (td) from a table header (th)?
[英]How to get the Id of corresponding th of td in a table
我有一个场景
<table>
<thead>
<tr>
<th id ="myid1">header1</th>
<th id ="myid2">headre "2</th>
<th id ="myid3">header3</th>
</tr>
</thead>
<tr>
<td>v1</td>
<td>v2</td>
<td>v3</td>
</tr>
<tr>
<td>v10</td>
<td>v11</td>
<td>v12</td>
</tr>
<tr>
<td>v20</td>
<td>v21</td>
<td>v22</td>
</tr>
<tr>
<td>v30</td>
<td>v31</td>
<td>v32</td>
</tr>
</table>
可能有成千上万的行。
我需要获取该pertedulat td所属的td的id。
例如 。 如果我点击第三行的第三个t ..我应该得到相应的id的id,这里是myid3(这里是硬编码但它将根据服务器端的值设置)
$('tbody td').live('click', function() {
var idOfTh = ??
});
$(function(){
$('td').click(function() {
alert($('table th').eq($(this).index()).attr('id'));
});
});
工作JSfiddle: http : //jsfiddle.net/6etRb/
如果动态添加表行,则只需要使用实时委派,在这种情况下,您应该使用其他人描述的.on()
。
以下答案是错误的,但我保留编辑,因为它可能会帮助某人
$('tbody td').live('click', function() {
var tdIndex = $(this).parent('tr').indexOf($(this));
var idOfTh = $(this).parent('table').find('tr').eq(tdIndex);
});
未经测试,但理论上应该有效。
更正
以上是不正确的,正如Felix Kling在下面指出的那样。 获取索引的正确方法是通过调用$(this).index()
。 我假设这会在匹配的选择器中找到$(this)
的位置(在这种情况下, <tbody>
中的每个<td>
<tbody>
),但实际上,如果你传递index()
函数没有参数,它会找到索引相对于其兄弟姐妹 。 感谢Felix指出相关文档 。
您可以使用eq()
方法,尝试以下方法:
$('tbody td').live('click', function() {
var ind = $(this).index()
var idOfTh = $('thead th:eq('+ind+')').attr('id')
});
请注意,不推荐使用live()
,而是可以使用on()
。
首先,不推荐使用.live()
函数。 如果要委派事件,请使用.on()
(jQuery 1.7+)或.delegate()
。 我假设您正在使用.on()
来完成剩下的工作,但是如果必须使用.on()
,则只需要进行少量语法更改(切换前两个参数.delegate()
。
$(document).on('click', 'tbody td', function() {
var tdIndex = $(this).index();
// ^ gets the index of the clicked element relative to its siblings
var thId = $('thead th:eq(' + tdIndex + ')')[0].id;
// ^ selects the th element in the same position in its row, then gets its id
});
这是你可以做到的一种方式:
$('td').click(function() {
var colNum = $(this).parent().children().index($(this)) + 1;
alert($('#myid' + colNum).text());
});
jsfiddle: http : //jsfiddle.net/p8SWW/4/
处理程序可以看起来像:
function() {
var self = this
var th_num = 0;
$(this).parent().children().each(function(num){
if (this == self) {
th_num = num;
return false
}
});
var th_id = $('thead th').eq(th_num).attr('id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.