【问题标题】:How do I get current rowindex of a table using Javascript?如何使用 Javascript 获取表的当前行索引?
【发布时间】:2016-10-01 02:44:40
【问题描述】:

我可以在 Javascript 中获取表的当前行索引吗?我们可以使用我们得到的当前索引删除表的行吗?

【问题讨论】:

  • 什么是当前行? - 此外,Get Current rowIndex of Table in Jquery 的可能重复项
  • 对不起,我的意思是我们可以得到特定的行索引吗?
  • 在上面的链接中直接回答
  • @SuperCoolHandsomeGelBoy 上面的链接是针对 jQuery,而不是纯 JavaScript。

标签: javascript html javascript-objects


【解决方案1】:

如果您使用的是 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;
    }
}

【讨论】:

  • 但我没有使用 jquery。
【解决方案2】:

默认情况下,事件对象将包含 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>

【讨论】:

  • 你的例子坏了
  • 错过id="demo" &lt;table&gt; 元素
【解决方案3】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多