最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSjQuery return TH of related TD, Possible? - Stack Overflow

programmeradmin20浏览0评论

I need to know if it's possible to get the .html() of a specific TH when it has no id or class set using jQuery selectors.

To illustrate my question:

TABLE
    THEAD TR
        TH1 TH2 TH3
    TBODY TR
        TD1 TD2 TD3

I set a $('table tbody tr td') function that turns a cell into an input field on a double click, then back into text on blur, reflecting the change made to the cell via the input field.

I need to be able to know which column I am accessing. So if someone double clicks TD2 I want the input field name to contain TH2.

Please let me know how I can do this without setting id/class's for each TH or TD.

I need to know if it's possible to get the .html() of a specific TH when it has no id or class set using jQuery selectors.

To illustrate my question:

TABLE
    THEAD TR
        TH1 TH2 TH3
    TBODY TR
        TD1 TD2 TD3

I set a $('table tbody tr td') function that turns a cell into an input field on a double click, then back into text on blur, reflecting the change made to the cell via the input field.

I need to be able to know which column I am accessing. So if someone double clicks TD2 I want the input field name to contain TH2.

Please let me know how I can do this without setting id/class's for each TH or TD.

Share Improve this question edited Jun 25, 2011 at 1:47 Kevin Ji 10.5k4 gold badges43 silver badges65 bronze badges asked Jun 24, 2011 at 23:22 Vitaliy IsikovVitaliy Isikov 3,6549 gold badges41 silver badges46 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 20

If the handler is on your <td> element, then in your handler:

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

Table cells maintain their own index numbers, accessible through the cellIndex property.

Table rows do the same thing via rowIndex.

The jQuery methods are:

  • the closest()[docs] method to get the <table>

  • the find()[docs] method to find the nested <th> elements

  • the eq()[docs] method to reduce the <th> elements down to the one at the same index as the <td>

A little further jQuery reduction could look like this:

var th = $(this).closest('table')[0].rows[0].cells[ this.cellIndex ];

How is this

$('td').click(function(){
    cell = this.cellIndex;
    alert( $(this).closest('table').find('th:eq('+cell+')').text());
});

A jQuery alternative to Patrick's solution could be:

$("td").click(function()
{
    var $this = $(this);

    //Find the index of the column based on how many 
    //previous TDs there are.
    var col_idx = $this.prevAll("td").length;

    //Now select the Nth TH in the table using the base 1 column index.
    var $th = $("th:nth-child(" + (col_idx + 1) + ")", $this.closest("table"));

    /* your other code */
});
发布评论

评论列表(0)

  1. 暂无评论