【问题标题】:Use JavaScript to target nth column in table or nth cell of every table row使用 JavaScript 定位表格中的第 n 列或每个表格行的第 n 个单元格
【发布时间】:2017-10-13 02:11:05
【问题描述】:

我正在尝试针对给定表格的点击事件定位特定列。我很难为每一行指定我的选择,或者理想情况下,选择特定索引的一整列 td 元素。到目前为止我所拥有的:

 sorter(d, i) {

        console.log(i);
        let n = i;
        let table = document.querySelector('tbody');
        let rows = table.querySelectorAll('tr');
        //let length = this.tableElements.length;

        let td = rows.cells[n];

        console.log(td);

    }

如果我使用: let td = rows[0].cells[n]; 我按预期从第一行的特定单元格索引中获得了我想要的选择。如何用这个指定每一行?我想使用此选择对表格进行排序。

谢谢!

【问题讨论】:

    标签: javascript html-table


    【解决方案1】:

    您可以迭代 rows 并返回一个值数组

    let tds = Array.from(rows, row => row.cells[n]);
    

    【讨论】:

    • 您可能也可以使用let tds = table.querySelectorAll("tr td:nth-child("+ i + 1 +")"),这取决于i 是什么,因为:nth-child() 伪类是基于1 的。
    【解决方案2】:
        sorter(d, i) {
    
                console.log(i);
                let n = i;
                let table = document.querySelector('tbody');
                let rows = table.querySelectorAll('tr');
                //let length = this.tableElements.length;
    var td;
            for(l=0;l<length;l++){
                 td = rows[l].cells[n];
    
                console.log(td);
        }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2016-11-10
      • 2023-03-21
      相关资源
      最近更新 更多