JS事件监听器的一种元素? [英] JS event listener for a type of element?

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

问题描述

有没有办法为某种类型的html元素添加某种侦听器?例如,如果我想在用户点击任何 p元素时调用一个函数

监听窗口 / 文档 / document.body 和请检查元素的类型及其父母的类型,因为如果您在<>内有< span> ; p> ,点击跨度不会触发段落中的点击。

 文档。 (target!== null){
()); if(target.tagName.toLowerCase()=== elementToLookFor){
//用段落
做些魔术东西console.log(target);
}
target = target .parentElement;
}
});

这项技术被称为事件委派。



编辑:请注意,您不能从上面的循环中尽早返回。如果您有嵌套段落,即

 < p> 
嘿,
< p>有!< / p>
< / p>

早期返回只会调用内部段落的事件处理程序,而您说' d喜欢在每个段落中调用的处理程序,这就是为什么您需要遍历元素的所有祖先。


Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element

解决方案

Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a <span> inside a <p>, clicking the span won't trigger the click in the paragraph.

document.addEventListener("click", function (eventArgs) {
    var target = eventArgs.target;
    var elementToLookFor = "p";
    while (target !== null) {
        if (target.tagName.toLowerCase() === elementToLookFor) {
            // Do magic stuff with the paragraph
            console.log(target);
        }
        target = target.parentElement;
    }
});

This technique is called "event delegation."

Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.

<p>
    Hey,
    <p>there!</p>
</p>

Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.

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

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