JS/jQuery return TH of related TD, Possible?
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开发者_JS百科 setting id/class's for each TH or TD.
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>
elementsthe
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 */
});
精彩评论