javascript - 查找单击的行的表格行号

标签 javascript dom

如何将功能添加到下面现有的 JavaScript 代码中,以找出单击的行号。表头应该被排除,并且数据集将从 ID 号 0 开始。

例如,如果单击表格的第二行,则会弹出一个警告框,提示“ID # 为 1”

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#mstrTable {
     border: 1px solid black
}
#mstrTable td, th {
     border: 1px solid black
}

#mstrTable tr.normal td {
    color: black;
    background-color: white;
}
#mstrTable tr.highlighted td {
    color: white;
    background-color: gray;
}
</style>
</head>
<body>
  <table id="mstrTable">
     <thead>
      <tr> 
        <th>File Number</th>
        <th>Date1</th>
        <th>Date2</th>
        <th>Status</th>
        <th>Num.</th>
      </tr>
    </thead>
    <tbody>
      <tr> 
        <td>KABC</td>
        <td>09/12/2002</td>
        <td>09/12/2002</td>
        <td>Submitted</td>
        <td>0</td>

      </tr>
      <tr> 
        <td>KCBS</td>
        <td>09/11/2002</td>
        <td>09/11/2002</td>
        <td>Approved</td>
        <td>1&nbsp;</td>
      </tr>

      <tr> 
        <td>WFLA</td>
        <td>09/11/2002</td>
        <td>09/11/2002</td>
        <td>Submitted</td>
        <td>2</td>
      </tr>
      <tr> 
        <td>WTSP</td>
        <td>09/15/2002</td>
        <td>09/15/2002</td>
        <td>In-Progress</td>
        <td>3</td>
      </tr>
    </tbody>
  </table>

<script type="text/javascript">
(
  function( )
  {
      var trows = document.getElementById("mstrTable").rows;

      for ( var t = 1; t < trows.length; ++t )
      {
          trow = trows[t];
          trow.className = "normal";
          trow.onclick = highlightRow;
      }

      function highlightRow( )
      {
          for ( var t = 1; t < trows.length; ++t )
          {
              trow = trows[t];
              trow.className = ( trow == this && trow.className != "highlighted") ? "highlighted" : "normal";
          }
      }
  }
)();
</script>
</body>
</html>

最佳答案

查看 rowIndex 属性 here 。从0开始。

关于javascript - 查找单击的行的表格行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14295519/

相关文章:

javascript - 更改结束日期时如何触发方法

javascript - 使用延迟触发方法

javascript - 如何在 Turbolinks 中使用 HTML 初始化 Flickity

javascript - 覆盖 native 功能?

javascript - 将样式应用于在 Polymer 中使用 InnerHTML 插入的元素

javascript - Chartjs 中的条形图未正确分组

javascript - Node.js 中的后台进程

javascript - 检索 HTML 元素的位置 (X,Y)

javascript - 如何检查所有父元素的可见性?

javascript - 防止 jQuery Elastic 插件在点击外部时缩小文本区域的大小