选择相关TD的行TH

时间:2013-11-18 15:01:28

标签: javascript jquery html

http://jsfiddle.net/wT3Ev/ 如何检索所选td的行TH中的文本?

是的,我发现了一些相关的帖子,但对我来说没有任何帮助。

我试过了:

$(document).on("click", "#sTab td,#pvTab td", function () {
alert($('#sTab tr').find('th:nth-child(' + $(this).parent().index() + ')').innerHTML);

alert($(this).parent());

var th = $(this).closest('table').find('th').eq( this.cellIndex );   

alert(th.innerHTML); 
}

4 个答案:

答案 0 :(得分:3)

我建议:

/* binds a click-handler to the 'tbody' element,
   filters those clicks to only those that originate on a 'td' element:
*/
$('tbody').on('click', 'td', function(){
    /* gets the siblings of the clicked 'td' element, filters those siblings
       for 'th' elements, gets the first of those matching elements,
       and then retrieves the text of that element, assigning it to the variable:
    */
    var thText = $(this).siblings('th').first().text();
    console.log(thText);
});

JS Fiddle demo

或者,使用更多的DOM(微小的,微小的效率提升):

// same as above:
$('tbody').on('click', 'td', function(){
    /* using DOM (not jQuery), moving from the clicked 'td' element
       to its parentNode ('tr'), retrieving the first of its children
       (JavaScript is zero-indexed, the first child is at position '0'),
       and retrieving its textContent (the text of the 'th'):
    */
    var thText = this.parentNode.children[0].textContent;
    console.log(thText);
});

JS Fiddle demo

参考文献:

答案 1 :(得分:1)

这应该有效:

var index = $(this).index();
console.log($(this).parents("table").find("th:eq(" + index + ")").text());

修改:标题:console.log($(this).closest("tr").find("th").text());

小提琴:http://jsfiddle.net/wT3Ev/4/

答案 2 :(得分:1)

你离我太远了。这适用于您的示例:

$(document).on("click", "#sTab td,#pvTab td", function () {
    var tdIndex = $(this).index(),
        table = $(this).closest('table'),
        headingIndex = tdIndex + 1,
        thText = table.find('th:nth-child(' + headingIndex + ')').text();
    alert(thText);
});

答案 3 :(得分:1)

$(this).parent().find('th').html();

编辑:说明 - 行总是单元格的父级,因此不需要查找索引 - 只需在有单元格的行中查找标题。

http://jsfiddle.net/qA6R9/