javascript - 选择 'tr' 元素内的兄弟元素

标签 javascript html dom

我有一个这样的表:

<table>
    <th>
        <!--the table heading-->
        <td>id</td>
        <td>type</td>
        <td>Price</td>
        <td>examine</td>
    </th>
    <tr>
        <td>0</td>
        <td>Book</td>
        <td>500</td>
        <button>examine</button> <!-- onclick, get the id value 0 -->
    </tr>
    <tr>
        <td>1</td>
        <td>Clothing</td>
        <td>30</td>
        <button>examine</button> <!-- onclick, get the id value 1 -->
    </tr>
    <tr>
        <td>2</td>
        <td>Food</td>
        <td>400</td>
        <button>examine</button> <!-- onclick, get the id value 2 -->
    </tr>
    <!--...
    there are 100 rows-->
    <tr>
        <td>99</td>
        <td>Book</td>
        <td>300</td>
        <button>examine</button> <!-- onclick, get the id value 99 -->
    </tr>
</table>

我想给按钮添加一个事件监听器,当我点击按钮时,它会获取相应的 id 值作为函数的参数传递。如何在不使用 JQuery 的情况下完成这项工作?

最佳答案

要稳健地执行此操作,您首先需要从按钮向上移动到祖先 TR(如果有的话),然后获取第一个单元格的文本内容,例如

// Starting at el, get ancestor with tagName
// If no such ancestor, return null
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();
  while (el.parentNode && el.parentNode.tagName) {
    el = el.parentNode;
    if (el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }
  return null;
}

// Add click listener to all buttons
window.onload = function() {
  [].forEach.call(document.querySelectorAll('button'),function(button) {
    button.addEventListener('click',function() {
      // Get the ancestor row
      var row = upTo(this, 'tr');
      if (row) {
        // If there is a first cell, log it's textContent
        console.log(row.cells[0] && row.cells[0].textContent);
      }
    },false);
  });
}
<table>
    <tr><th>id<th>type<th>Price<th>examine
    <tr><td>0<td>Book<td>500<td><button>examine</button>
    <tr><td>1<td>Clothing<td>30<td><button>examine</button>
</table>

这会将监听器添加到所有按钮,您可能希望对其进行限制。还修复了 HTML 以将按钮放在单元格中,并添加了第一行。

关于javascript - 选择 'tr' 元素内的兄弟元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42661422/

相关文章:

javascript - 如何从 React 中的 cdn/script 标签导入 javascript 包?

javascript - 如何使用自定义ajax函数通过id或class参数提交表单

javascript - 我有多个带有复选框及其值的 <td>。我想更改 <td> 的颜色

jquery - 如何通过使用 jquery 添加该表的行来获取表总数

javascript - 忽略/覆盖周围/继承的 CSS

javascript - 使用 jQuery .each() 方法连接多个数组

javascript - `document.elementFromPoint` 的 puppeteer api 是什么?

javascript - 即使 jQuery 中不满足条件也执行 else 语句

javascript - Next.js getInitialProps cookies

javascript - JavaScript 宿主对象是如何实现的?