[英]How do I get current rowindex of a table using Javascript?
我可以在 Javascript 中獲取表的當前行索引嗎,我們可以使用我們得到的當前索引刪除表的行嗎?
rowIndex 屬性返回表中行的位置
function myFunction(x) { console.log("Row index is: " + x.rowIndex); }
<table> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> </table>
如果您使用 JQuery,請使用方法.index()
var index = $('table tr').index(tr);
如果沒有使用 JQuery,您可以遍歷所有 TR 元素以找到匹配的 TR。
var index = -1;
var rows = document.getElementById("yourTable").rows;
for (var i=0;i<rows.length; i++){
if ( rows[i] == YOUR_TR ){
index = i;
break;
}
}
默認情況下,事件對象將包含 rowindex 屬性
function myFunction() { var x = document.getElementsByTagName("tr"); var txt = ""; var i; for (i = 0; i < x.length; i++) { txt = txt + "The index of Row " + (i + 1) + " is: " + x[i].rowIndex + "<br>"; } document.getElementById("demo").innerHTML = txt; }
<table> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.