[英]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);
}
}
表格元素具有rowIndex
或cellIndex
等屬性,您不需要為每個單元格使用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.