【问题标题】:Get html table row and cell index with javascript function使用javascript函数获取html表格行和单元格索引
【发布时间】:2021-03-06 11:44:31
【问题描述】:

我需要根据用户在表格中的点击返回行和单元格索引。

我的功能:

function updatePrice()
{
    var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];

    for(var i = 0; i < table.rows.length; i++){
        table.rows[i].onclick = function valorLinha() {
            rIndex = this.rowIndex;
            /*console.log here works fine*/
        };
        for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                cellIndex = this.cellIndex;
        };

  
        /*I NEED values of rIndex and cellIndex here*/
        console.log(rIndex);
        console.log(cellIndex);
    }
}

console.log 运行时我变得不确定。

我该如何解决这个问题?

【问题讨论】:

  • I NEED values of rIndex and cellIndex here 不,你没有。唯一需要它们的地方(以及拥有它们的地方)是在点击处理函数内部。 jsfiddle.net/5ork1x0h
  • 好的,谢谢回复。我用这段代码解决了我的问题:morioh.com/p/aae77200692f

标签: javascript


【解决方案1】:
var table = document.getElementsByTagName('table')[0];
for (let i = 0; i < table.rows.length; i++) {
    for (let j = 0; j < table.rows[i].cells.length; j++){
        table.rows[i].cells[j].onclick = function(){
            console.log("Row = "+i+" Cell = "+j)
        }
    }
}

【讨论】:

    【解决方案2】:

    rIndex 与循环中的 i 变量相同 而 cellIndex 是一个你应该循环它的集合

    function updatePrice()
    {
        var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];
    
        for(var i = 0; i < table.rows.length; i++){
            var rowi = table.rows[i];
            // rIndex = rowi.rowIndex = i;
            rIndex = i;
            console.log(rIndex);
    
            // cellIndex are multiple, you should loop
    
            for (var j = 0; j < rowi.cells.length; j++){
                var cellj = rowi.cells[j];
                cellIndex = cellj.cellIndex;console.log(cellIndex);
            } 
        }
    }```
    

    【讨论】:

      【解决方案3】:

       document.querySelectorAll('#table td')
      .forEach(e => e.addEventListener("click", function() {
          // Here, `this` refers to the element the event was hooked on
          console.log("clicked cell at: " + this.cellIndex + ", " + this.parentNode.rowIndex);
      }));
      td{
      cursor:pointer;
      }
      <table id="table">
          <tbody>
            <tr>
              <td>00</td>
              <td>10</td>
            </tr>
            <tr>
              <td>01</td>
              <td>11</td>
            </tr>
            <tr>
              <td>02</td>
              <td>12</td>
            </tr>
          </tbody>
        </table>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-08
        • 2013-06-24
        • 2019-02-26
        • 2012-10-16
        • 2020-01-06
        • 2021-10-31
        • 2016-08-28
        • 2012-09-28
        相关资源
        最近更新 更多