[英]How to get Dropdownlist value on HTML Table Cell in a Row using javascript
[英]Get html table row and cell index with javascript function
我需要根據用戶在表格中的點擊返回行和單元格索引。
我的 function:
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 運行時,我變得不確定。
我該如何解決這個問題?
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)
}
}
}
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);
}
}
}```
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.