How do i get current rowindex of table using javas

2019-03-07 02:38发布

Hello today I have one question. Can I get current row index of table in javascript ? and can we remove row of table with current Index that we got?

3条回答
Explosion°爆炸
2楼-- · 2019-03-07 03:38

If you are using JQuery, use method .index()

var index = $('table tr').index(tr);

If no JQuery used, you can loop through all the TR element to find the matched 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;
    }
}
查看更多
Summer. ? 凉城
3楼-- · 2019-03-07 03:40

The rowIndex property returns the position of a row in table

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>

查看更多
做个烂人
4楼-- · 2019-03-07 03:42

By default the event object will contain the rowindex property

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>

查看更多
登录 后发表回答