问题描述
|
我需要知道当没有使用jQuery选择器设置的id或类时,是否可以获得特定TH的“ 0”。
为了说明我的问题:
TABLE
THEAD TR
TH1 TH2 TH3
TBODY TR
TD1 TD2 TD3
我设置了一个“ 2”功能,双击该功能可以将一个单元格变成一个输入字段,然后在模糊时返回到文本,以反映通过输入字段对单元格所做的更改。
我需要能够知道我正在访问哪一列。因此,如果有人双击TD2,我希望输入字段名称包含TH2。
请让我知道如何在不为每个TH或TD设置id / class的情况下执行此操作。
解决方法
如果处理程序在您的
<td>
元素上,则在您的处理程序中:
var th = $(this).closest(\'table\').find(\'th\').eq( this.cellIndex );
表格单元格维护自己的索引号,可通过ѭ5属性访问。
表格行通过ѭ6进行相同的操作。
jQuery方法是:
closest()
[docs]方法获得<table>
find()
[docs]方法来查找嵌套的<th>
元素
eq()
[docs]方法可将<th>
元素减少到与<td>
索引相同的元素
进一步简化jQuery可能看起来像这样:
var th = $(this).closest(\'table\')[0].rows[0].cells[ this.cellIndex ];
, 这怎么样
$(\'td\').click(function(){
cell = this.cellIndex;
alert( $(this).closest(\'table\').find(\'th:eq(\'+cell+\')\').text());
});
, 帕特里克解决方案的jQuery替代方案可能是:
$(\"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 */
});