多个事件监听器没有循环

时间:2016-02-15 13:48:18

标签: javascript

我的项目中有相同的结构!

<!-- menu structure-->
   <nav class="menu">
       <a class="trigger" href="#">item</a>
       <a class="trigger" href="#">item</a>
       <a class="trigger" href="#">item</a>
       <a class="trigger" href="#">item</a>
       <a class="trigger" href="#">item</a>
   </nav>

我想为所有触发器添加一个事件监听器,但我找到的解决方案是使用循环,这里是js

menuitens = document.querySelectorAll('.trigger');
menuitens.addEventListener("click", function (){});

2 个答案:

答案 0 :(得分:0)

要让单个事件侦听器将其绑定到容器,而不是:

document.querySelector('.menu').addEventListener('click', function(e) {
    e.preventDefault();

    if (!e.target.classList.contains('trigger')) return;

    alert('.trigger clicked');
});

https://jsfiddle.net/t6frderh/

答案 1 :(得分:0)

您可以收听容器元素上的所有点击事件:

SELECT 
    c 
FROM 
     CRMBundle:TblCompanyDomain cd 
     INNER JOIN cd.company c 
     LEFT JOIN CRMBundle:TblCompanyAddress ca WITH ca.company = c
     INNER JOIN ca.country cc 
WHERE 
     cd.domain IN(:domain) AND 
     c.channel = :channel_id