HTML元素列表上的事件侦听器 [英] Event listener on List of HTML Elements

查看:67
本文介绍了HTML元素列表上的事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DOM中有多个具有相同类名的元素-'ps__rail-y'.我想遍历这些元素,并使用类侦听单个元素上的click事件,并停止事件传播.我已经尝试过以下方法,但是不知何故.

I have multiple elements in DOM with the same class name - 'ps__rail-y'. I want to iterateover those elements and listen to click event on individual element with the class and stop event propagation. I have tried the approach below, but somehow it is not working.

onClickScrollBar(){
    let elements : Array<any> = this._elRef.nativeElement.querySelectorAll('.ps__rail-y');
    elements.forEach((index : number) => {
      let element = document.getElementsByClassName('ps__rail-y')[index] as HTMLElement;
      element.addEventListener('click', (e : Event) => {
        e.stopPropagation()
      }, true)
    })
  }

推荐答案

第一个

First document.getElementsByClassName('ps__rail-y')\[index\] is really bad code.

实际上,最好的办法是利用事件委托",在该事件委托中,您仅在可能"处理所有元素的祖先处设置一个事件处理程序.触发事件,然后让事件冒充到那个祖先.然后,在祖先处理完该事件后,您可以引用 event.target ,它将引用引发该事件的实际元素.这样,您只需设置一个处理程序即可,而无需设置多个处理程序,而且无需任何循环.

Really, the best thing to do is to utilize "event delegation", where you only set up one event handler at an ancestor of all the elements that "might" trigger the event and let the event bubble up to that ancestor. Then, when it is handled at the ancestor, you can reference the event.target, which will reference the actual element that initiated the event. This way, you only set up one handler instead of many and you do it without any looping.

这是一个例子:

// Set up the handler at an ancestor
document.querySelector("section").addEventListener("click", function(event){
  // Only act if the actual element that triggered the event
  // has a certain class
  if(event.target.classList.contains("foo")){
    console.log("You clicked the " + event.target.nodeName + " element.");
  }
});

<section>
  <div class="foo">Click me</div>
  <h1 class="foo">Click me</h1>
  <div>Click me  <span>Click me</span></div>
  <p>Click me</p>  
  <a href="#" class="foo">Click me</a>  
</section>

这篇关于HTML元素列表上的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆