简体   繁体   English

如何使用event.target获取元素的子级

[英]How to get the child of a element with event.target

I'm trying to get the child elements of a div to toggle a class 'active' 我正在尝试获取div的子元素来切换类“活动”

JS JS

    const dots = document.querySelectorAll('[data-dots]');
    dots.forEach(dot => dot.addEventListener('click', handleClick));

    function handleClick(e) {
     e.target.getElementsByClassName('tb-drop').classList.toggle('active');
     console.log(e.target.getElementsByClassName('tb-drop'))
    }

HTML 的HTML

       <div class="dots" data-dots>
         <i class="fas fa-ellipsis-v dots"></i>
         <div class="tb-drop">
            <i class="far fa-edit icon-grid"></i>
            <i class="fas fa-link icon-grid"></i>
         </div>
       </div>

So i'm selecting all the divs with the data-dots attribute and then select the child of that div and add the class active. 所以我要选择所有具有data-dots属性的div,然后选择该div的子级并添加active类。 I tried with e.target.children but didnt work. 我尝试了e.target.children,但没有工作。

Thanks, I'm just trying to learn :) 谢谢,我只是想学习:)

In order to identify the first child, the easiest option is simply to use Element.querySelector() in place of Element.getElementsByClassName() : 为了识别第一个孩子,最简单的选择就是简单地使用Element.querySelector()代替Element.getElementsByClassName()

const dots = document.querySelectorAll('[data-dots]');
dots.forEach(dot => dot.addEventListener('click', handleClick));

function handleClick(e) {
  // Element.querySelector() returns the first - if any -
  // element matching the supplied CSS selector (element,
  // elements):
  e.target.querySelector('.tb-drop').classList.add('active');
}

The problem is, of course, that if no matching element is found by Element.querySelector() then it returns null ; 当然,问题在于,如果Element.querySelector()没有找到匹配的元素,则它返回null ;否则,返回null which is where your script will raise an error. 这是您的脚本将引发错误的地方。 So, with that in mind, it makes sense to check that the element exists before you try to modify it: 因此,考虑到这一点,在尝试修改元素之前先检查该元素是否存在是有意义的:

const dots = document.querySelectorAll('[data-dots]');
dots.forEach(dot => dot.addEventListener('click', handleClick));

function handleClick(e) {
  let el = e.target.querySelector('.tb-drop');
  if (el) {
    el.classList.add('active');
  }
}

It's also worth noting that EventTarget.addEventListener() passes the this element into the function, so rather than using: 还值得注意的是, EventTarget.addEventListener()this元素传递给函数,因此不要使用:

e.target.querySelector(...)

it's entirely possible to simply write: 完全可以简单地编写:

this.querySelector(...)

Unless, of course, handleClick() is rewritten as an Arrow function. 当然,除非将handleClick()重写为Arrow函数。

Demo: 演示:

 const dots = document.querySelectorAll('[data-dots]'); dots.forEach(dot => dot.addEventListener('click', handleClick)); function handleClick(e) { let el = e.target.querySelector('.tb-drop'); if (el) { el.classList.add('active'); } } 
 div { display: block; border: 2px solid #000; padding: 0.5em; } i { display: inline-block; height: 1em; } ::before { content: attr(class); } .active { color: limegreen; } 
 <div class="dots" data-dots> <i class="fas fa-ellipsis-v dots"></i> <div class="tb-drop"> <i class="far fa-edit icon-grid"></i> <i class="fas fa-link icon-grid"></i> </div> </div> 

Or, if you wish to toggle the 'active' class you could, instead, use toggle() in place of add : 或者,如果您希望切换“活动”类,则可以使用toggle()代替add

 const dots = document.querySelectorAll('[data-dots]'); dots.forEach(dot => dot.addEventListener('click', handleClick)); function handleClick(e) { let el = e.target.querySelector('.tb-drop'); if (el) { el.classList.toggle('active'); } } 
 div { display: block; border: 2px solid #000; padding: 0.5em; } i { display: inline-block; height: 1em; } ::before { content: attr(class); } .active { color: limegreen; } 
 <div class="dots" data-dots> <i class="fas fa-ellipsis-v dots"></i> <div class="tb-drop"> <i class="far fa-edit icon-grid"></i> <i class="fas fa-link icon-grid"></i> </div> </div> 

References: 参考文献:

e.target already is the clicked child of the element that you installed the listener on. e.target已经安装侦听器的元素的单击子元素。 You probably want to use e.currentTarget or this instead. 您可能想要使用e.currentTargetthis
Then you can go using .getElementsByClassName() , .querySelector[All]() or .children from there. 然后你可以去使用.getElementsByClassName() .querySelector[All]().children从那里。

You can also try this code. 您也可以尝试此代码。

 var dots = document.querySelectorAll('[data-dots]');
  for (var i = 0; i < dots.length; i++) {
      dots[i].addEventListener('click', function () {
          handleClick(this);
      }, false);
  }

function handleClick(object) {
     var container = object.getElementsByClassName('tb-drop')[0];
     if (container != undefined) {
        if (container.classList.contains('active')) {
            container.classList.remove('active')
        }else{
            container.classList.add('active')
        } 
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM