如何使用 Javascript 获取表的当前行索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37573622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get current rowindex of a table using Javascript?
提问by nara son
Can I get current row index of a table in Javascript and can we remove the row of table with current Index that we got?
我可以在 Javascript 中获取表的当前行索引吗,我们可以使用我们得到的当前索引删除表的行吗?
回答by Mahendra Kulkarni
The rowIndex property returns the position of a row in table
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>
回答by Felton Fei
If you are using JQuery, use method .index()
如果您使用 JQuery,请使用方法.index()
var index = $('table tr').index(tr);
If no JQuery used, you can loop through all the TR element to find the matched 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;
}
}
回答by kirubakar
By default the event object will contain the rowindex property
默认情况下,事件对象将包含 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>