首页 > 解决方案 > vanilla JS 中的 DOM 操作

问题描述

当有多个相同类的元素时,如何访问单击事件的父元素?我正在尝试修改最接近的兄弟姐妹的内容。

该示例包含一个 jQuery 版本的它应该做什么。

我使用 'document' 作为 eventlisterner,因为 '.interactive-btn' 是动态添加的元素。

https://jsfiddle.net/gb8tr0nu/2/

HTML:

<table class="my-table">
  <thead>
    <tr>
      <th>Account</th>
      <th>Note</th>
      <th>Time</th>
    </tr>  
  </thead>
  <tbody>
    <tr>
      <td class="account">account one</td>
      <td class="note">1234567890</td>
      <td class="time">7/10/2018
          <button class="interactive-btn">Button</button>
      </td>
    </tr>
    <tr>
      <td class="account">account two</td>
      <td class="note">abcdefghijklmn</td>
      <td class="time">7/10/2018
          <button class="interactive-btn">Button</button>
      </td>
    </tr>
  </tbody>
</table>

JS:

/* Vanilla */
document.addEventListener('click', (event) => {
  if(event.target.className === 'interactive-btn') {
        // get the closest .note content and chagne it.     
  }
});

/* Jquery */
$(document).on('click', '.interactive-btn', function(event) {
    $(this).parent().siblings('.note').text('new text');
});

标签: javascriptjquerydom

解决方案


如果您可以使用实验性功能,您可以使用Element.closest查找祖先tr,然后使用document.querySelectorCSS 选择器查找td带有class="note".

我还使用了一个更丑陋(但仍然有效)的解决方案Node.parentElement- 如果您重组 HTML,这将打破!

document.addEventListener('click', (event) => {
  /*if (event.target.className === 'interactive-btn') {
    //looks nice, but experimental - probably shouldn't be used in production code
    var noteEl = event.target.closest('tr').querySelector('td[class=note]');

    noteEl.innerHTML = 'Changed!'
  }
});*/

  if (event.target.className === 'interactive-btn') {
    //a little uglier but works if your HTML structure doesnt change
    var noteEl = event.target.parentElement.parentElement.querySelector('td[class=note]');

    noteEl.innerHTML = 'Changed!'
  }
});
<table class="my-table">
  <thead>
    <tr>
      <th>Account</th>
      <th>Note</th>
      <th>Time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="account">account one</td>
      <td class="note">1234567890</td>
      <td class="time">7/10/2018
        <button class="interactive-btn">Button</button>
      </td>
    </tr>
    <tr>
      <td class="account">account two</td>
      <td class="note">abcdefghijklmn</td>
      <td class="time">7/10/2018
        <button class="interactive-btn">Button</button>
      </td>
    </tr>
  </tbody>
</table>


推荐阅读