Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS/jQuery返回相关TD的TH,可能吗?_Javascript_Jquery_Jquery Selectors - Fatal编程技术网

Javascript JS/jQuery返回相关TD的TH,可能吗?

Javascript JS/jQuery返回相关TD的TH,可能吗?,javascript,jquery,jquery-selectors,Javascript,Jquery,Jquery Selectors,我需要知道,当特定TH没有使用jQuery选择器设置id或类时,是否可以获取该TH的.html() 为了说明我的问题: TABLE THEAD TR TH1 TH2 TH3 TBODY TR TD1 TD2 TD3 我设置了一个$('table tbody tr td')函数,双击该函数可将单元格转换为输入字段,然后在模糊时返回文本,反映通过输入字段对单元格所做的更改 我需要能够知道我正在访问哪个专栏。因此,如果有人双击TD2,我希望输入字段名包

我需要知道,当特定TH没有使用jQuery选择器设置id或类时,是否可以获取该TH的
.html()

为了说明我的问题:

TABLE
    THEAD TR
        TH1 TH2 TH3
    TBODY TR
        TD1 TD2 TD3
我设置了一个
$('table tbody tr td')
函数,双击该函数可将单元格转换为输入字段,然后在模糊时返回文本,反映通过输入字段对单元格所做的更改

我需要能够知道我正在访问哪个专栏。因此,如果有人双击TD2,我希望输入字段名包含TH2


请告诉我如何在不为每个TH或TD设置id/class的情况下执行此操作。

如果处理程序位于
元素上,则在处理程序中:

var th = $(this).closest('table').find('th').eq( this.cellIndex );
表格单元格维护自己的索引编号,可通过
cellIndex
属性访问

表行通过
rowIndex
执行相同的操作

jQuery方法包括:

  • 获取

  • 查找嵌套的
    元素的方法

  • 元素缩减为与
    具有相同索引的元素的方法

进一步简化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());
});

Patrick解决方案的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 */
});

@乔纳森:@Gaby:谢谢。我喜欢那些罕见的兼容浏览器的功能,它们特别有用,比如行和单元格索引。