如何在单击事件中获取子元素

3
我正在给一个按钮添加点击事件,并且我需要获取此按钮的父级,然后我需要获取该父级的特定子级。
问题还在于我有多个这些按钮及其对应的容器和子元素。
我已经为每个按钮添加了点击事件,但似乎不能独立地获取这些按钮的元素。
HTML
<div class="parentContainer">
     <div class="otherElement"></div>

     <a class="button">

     <div class="childElement"></div>
</div>

JS

var btn = document.querySelectorAll(".button");

for (let i = 0; i < button.length; i++){
    button[i].addEventListener('click', function(){

        var container = this.closest('.parentContainer');
        var j = 0;

        for(j = 0; j < container.length; j++){ 
            if(j.classList.contains('childElement')){
                j.classList.add('Example')
            } else {
                container.style.background = "white";
            }
        };
    });
}

对于特定的按钮点击,其兄弟元素(childElement)应该获得一个名为“Example”的类。

如果我们了解您想要实现的最终结果,可能会帮助我们提供更好的建议 - 您是否想要为子元素设置样式?您是否触发异步函数来执行某些操作?您是否需要影响另一个元素的状态以触发其他函数? - Tom 'Blue' Piddock
我正在尝试将一个类添加到“.childElement”作为最终结果。 - Mat Mol
3个回答

6
您可以使用事件委托技术来简化此过程 - 这样,您的代码只需要一个事件处理程序,而不是针对代码中每个“按钮”的单独处理程序。一旦设置了事件处理程序,您就可以利用DOM API在适当的父元素下查找.otherElement元素。我添加了一些“按钮”到您的代码中,以展示无论您添加多少“按钮”,它都能很好地工作:

const log = e => {
  console.clear();
  console.log(`${e.target.parentNode.previousElementSibling.dataset.about}`);
};
document.querySelector('.parentContainer').addEventListener('click', e => {
  if (e.target.classList.contains('childElement')) {
    e.target.classList.toggle('example');
    log(e);
  }
});
.example {
  color: green;
  font-size: 32px;
  font-weight: bold;
}
<div class="parentContainer">
  <div class="otherElement" data-about="This is otherElement for Button 1"></div>
  <a class="button">
    <div class="childElement">Button 1</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 2"></div>
  <a class="button">
    <div class="childElement">Button 2</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 3"></div>
  <a class="button">
    <div class="childElement">Button 3</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 4"></div>
  <a class="button">
    <div class="childElement">Button 4</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 5"></div>
  <a class="button">
    <div class="childElement">Button 5</div>
  </a>
</div>


抱歉,在我的初始描述中我忘记关闭<a>标签。但是尝试了您的解决方案后,我学到了一种新的方法!谢谢! - Mat Mol

4
您可以更加简单地完成它。

// check if there is at least one .button (this prevents javascript errors)
if (document.querySelector('.button')) {

  // select all buttons, each as el
  document.querySelectorAll('.button').forEach(function(el) {

    // bind click event to each el
    el.addEventListener('click', function (e) {
    
      // check also if there is at least on .childelement
      // e.target is the clicked element, parentNode the parent, from there find .childElement
      if (e.target.parentNode.querySelector('.childElement')) {
        e.target.parentNode.querySelector('.childElement').classList.add('Example');
      }
      else {
        e.target.parentNode.style.background = 'white';
      }
      
    });

   });

}
<div class="parentContainer">
     <div class="otherElement">otherElement</div>

     <a class="button">button</a>

     <div class="childElement">childElement</div>
</div>


1
你可以使用jQuery来实现类似以下的操作:
jQuery('button').click(function(){
    jQuery(this).next().addClass('example');
});

在我写的场景中,我假设你的HTML看起来像这样:
<div>
    <button></button>
    <div></div>
</div>

<div>
    <button></button>
    <div></div>
</div>

这很有用,但我不能在这个项目中使用jQuery :/ 我正在尝试仅使用JS完成此项目。 - Mat Mol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接