【问题标题】:Get table row index from row ID in TypeScript [duplicate]从 TypeScript 中的行 ID 获取表行索引 [重复]
【发布时间】:2018-04-23 09:06:53
【问题描述】:

我有一张桌子。每行都有一个 ID。

我可以通过仅使用其 ID(不点击)而不使用循环来获取任何行的索引吗?

我的 HTML 如下所示:

<table id="tabId">
<tr id="a">
    <td>ss</td>
    <td>ss</td>
</tr>
<tr id="b">
    <td>kk</td>
    <td>kk</td>
</tr> 

我试过了:

var row_number = document.getElementById('a').rowIndex;

但它不起作用;我收到一个error message 说:

[ts] 类型“HTMLElement”上不存在属性“rowIndex”。

【问题讨论】:

标签: html angular typescript


【解决方案1】:
document.getElementsByTagName("tr")[index].id;


<table id="tableId">
    <tr id="a">
        <td>a</td>
    </tr>
    <tr id="b">
        <td>b</td>
    </tr>
</table>

var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);

【讨论】:

  • 问题是 “我可以通过 id 使用循环获取任何行的行索引吗?” 而不是如何使用这个索引 O.o
  • 我需要相反的。
【解决方案2】:

您忘记将'' 添加到getElementById() 函数中并且您将rowIndex 写为不是属性并且错误。

这是一个工作示例:

var row_number = document.getElementById('a').rowIndex;
alert(row_number);
<table id="tabId">
<tr id="a">
    <td>ss</td>
    <td>ss</td>
</tr>
<tr id="b">
    <td>kk</td>
    <td>kk</td>
</tr> 

【讨论】:

  • 行索引在 htmlelement 类型上不存在。
  • 你确定你写的都是对的吗?你能再发布你的代码吗?
  • @user2243952 那你做错了什么。运行sn -p,你会发现它可以工作了
  • 我举了一个更简单的例子,但我的行 ID 是 {{item.id}}。我正在使用角度和打字稿
  • “HTMLElement”类型上不存在属性“rowIndex”。
【解决方案3】:
var rows = Array.prototype.slice.call(document.getElementById('tabId').rows);
var row = document.getElementById('b');

console.log(rows.indexOf(row));

这是Example

【讨论】:

  • “HTMLElement”类型上不存在属性“行”。
  • @klugjo,向答案正文本身添加额外的解释(例如(示例链接))总是一个好主意。
  • 知道了。我在评论说它不起作用之后创建了这个例子。下次会考虑编辑我的答案
【解决方案4】:

您可以使用on click on particulate tr 获取其index

或将您的Rowindex 更改为rowIndex 并在id of div 'a' in script 中添加''

function myFunction(x) {
  console.log("Row index is: " + x.rowIndex);
}
<table id="tabId">
  <tr id="a" onclick="myFunction(this)">
    <td>ss</td>
    <td>ss</td>
  </tr>
  <tr id="b" onclick="myFunction(this)">
    <td>kk</td>
    <td>kk</td>
  </tr>

【讨论】:

  • 我不会点击行。我只想通过仅使用 id 来获取行索引。
  • 所以把你的解决方案错误放在代码中所以解决这个问题
【解决方案5】:
var el = (document.getElementById('b')) as HTMLTableRowElement;
console.log(el.rowIndex);

【讨论】:

    【解决方案6】:

    特别感谢@durga 的解决方案。我通过将变量显式键入为 any 来修复它。

    var el : any = (document.getElementById('a')) as HTMLTableElement;
    var index = el.rowIndex;
    console.log(index);  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 2012-10-11
      • 2021-10-29
      • 2011-08-14
      • 2019-09-24
      相关资源
      最近更新 更多