繁体   English   中英

我如何获取表格的单元格ID

[英]How do i get the cell id of a table

这是板图function

this.drawBoard=function(){         
                document.write('<table id="newGame">');
                for(let i=0;i<boxes;i++){
                    document.write('<tr>');
                    for(let j=0;j<boxes;j++){
                    document.write(' <td id=" '+ i +' , '+ j + ' " ');
                    document.write('</td>'); 
                    }
                    document.write('</tr>');
        
                }
                document.write('</table>');
                b.onClickEvent();
        
            }
    

虽然这是获取 id 的 function

我发现通过更改行中的0索引clicked = cell.getElementsByTagName("td")[0].id; 我可以到达我想要的列,但不知道如何操作它以获得确切的单元格 ID

this.onClickEvent=function() {
                let table = document.getElementById("newGame");
                let rows = table.getElementsByTagName("tr");
                for (i = 0; i < rows.length; i++) {
                    let  currentRow = table.rows[i];
                    var createClickHandler =
                      function(cell) {
                        return function() {
                          clicked = cell.getElementsByTagName("td")[0].id;
                          console.log(clicked);
                          let numbers=[];
                          clicked.replace(/(\d[\d\.]*)/g, function( x ) { var n = Number(x); if (x == n) { numbers.push(x); }  })
                          b.spliceGrid(numbers[0],numbers[1]);
                          numbers=[];
                    
                    
                    };
                  };

                  currentRow.onclick = createClickHandler(currentRow);
            }
        
      }

表格元素具有rowIndexcellIndex等属性,您不需要为每个单元格使用id

这边走:

 function newTable(rowCount,cellCount) { const TableX = document.body.appendChild(document.createElement('table')) for( let r=0;r<rowCount;++r) { let newRow = TableX.insertRow() for(c=0;c<cellCount;++c) { newRow.insertCell().textContent = `${r},${c}` } } TableX.onclick = e => { if(.e.target.matches('td')) return let row = e.target.closest('tr') console.clear() console:log('clicked on,'. row,rowIndex. e.target,cellIndex ) } } newTable(4,5)
 table { border-collapse: collapse; } table td { padding: .2em.8em; border: 1px solid darkblue; text-align: center; cursor: pointer; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM