【问题标题】:Get the table row id on click点击获取表格行ID
【发布时间】:2016-12-15 14:16:36
【问题描述】:

我有这个<td> 标签:

<td align="center">
   <div class="dropdown">
      <button onclick="myFunction()" class="btn btn-default glyphicon glyphicon-picture" id=@TableRowId></button>
         <div id="myDropdown" class="dropdown-content">
            <a href="#">Show</a>
            <a href="#">Edit</a> 
         </div>
   </div>
</td>

还有这个 JavaScript 函数:

function myFunction() {
   document.getElementById("myDropdown").classList.toggle("show");
}

桌子图片:

点击图片打开该行的下拉菜单时,我需要获取特定的ID行。

我有一个 ID 迭代器:@TableRowId,它获取行号。

【问题讨论】:

  • 行在哪里?图片在哪里?
  • 我想在点击图片图标时,打开下拉菜单,我需要知道它的行ID,否则,我每次点击,下拉菜单都会从第一行删除。
  • 检查我的回答人。这是你需要的吗?

标签: javascript html css row


【解决方案1】:

假设您有一个表和tr,您可以使用parentNode 检索tr id:

function myFunction(el) {
  var id = el.parentNode.parentNode.parentNode.id;
  console.log(id);
  var all = document.querySelectorAll('.dropdown-content');
  for (var i = 0; i < all.length; i++) {
     all[i].classList.remove('show');
  }
  document.getElementById(id).querySelector('.dropdown-content').classList.toggle("show");
}
.dropdown-content{
  display: none;
}
.show{
  display: block;
}
<table>
  <tr id='id_1'>
    <td align="center">
      <div class="dropdown">
        <button onclick="myFunction(this)" class="btn btn-default glyphicon glyphicon-picture" id=@TableRowId>Click here</button>
        <div id="myDropdown" class="dropdown-content">
          <a href="#">Show</a>
          <a href="#">Edit</a> 
        </div>
      </div>
  </tr>
  <tr id='id_2'>
    <td align="center">
      <div class="dropdown">
        <button onclick="myFunction(this)" class="btn btn-default glyphicon glyphicon-picture" id=@TableRowId>Click here</button>
        <div id="myDropdown_2" class="dropdown-content">
          <a href="#">Show</a>
          <a href="#">Edit</a> 
        </div>
      </div>
  </tr>
  <tr id='id_3'>
    <td align="center">
      <div class="dropdown">
        <button onclick="myFunction(this)" class="btn btn-default glyphicon glyphicon-picture" id=@TableRowId>Click here</button>
        <div id="myDropdown_3" class="dropdown-content">
          <a href="#">Show</a>
          <a href="#">Edit</a> 
        </div>
      </div>
  </tr>
</table>

【讨论】:

  • 我想我需要那个 div 元素:
  • 现在检查。这是你需要的吗?
【解决方案2】:

尝试在 onclick 属性onclick="myFunction(this.id)" 中将 id 传递给您的函数。然后更改您的函数定义以包含该参数function myFunction(id) { ...

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签