How do I get current rowindex of a table using Javascript?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-20 07:48:03

问题


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?


回答1:


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>



回答2:


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;
    }
}



回答3:


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>


来源:https://stackoverflow.com/questions/37573622/how-do-i-get-current-rowindex-of-a-table-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!