将事件监听器添加到香草javascript中尚不存在的元素 [英] Adding an event listener to an element that doesn't exist yet in vanilla javascript
问题描述
在JQuery中,我可以做:
In JQuery I can do:
$(document).on("click","a.someBtn",function(e){
console.log("hi");
});
将事件侦听器添加到尚不存在的元素.我似乎无法弄清楚如何将事件侦听器添加到香草javascript中尚不存在的元素.
以下显然不起作用:
to add an event listener to an element that doesn't exist yet. I cannot seem to figure out how to add an event listener to an element that does not exist yet in vanilla javascript.
The following does not work obviously:
query.addEventListener( "click", someListener );
修改
我想做的是通过查询选择器比较项目.我正在选择querySelectorAll
尚不存在的元素.它比仅检查标签名称更具动态性.
What I would like to do is compare the item by query selectors. I am selecting the element that does not exist yet with querySelectorAll
. It is a little more dynamic than just checking the tag name.
推荐答案
使用目标属性(位于event
对象中)以获取被单击的元素.然后,手动测试类型/属性/ID
Use the target property in the event
object to get the clicked element. Then, manually test for type/attributes/ids
document.addEventListener( "click", someListener );
function someListener(event){
var element = event.target;
if(element.tagName == 'A' && element.classList.contains("someBtn")){
console.log("hi");
}
}
这篇关于将事件监听器添加到香草javascript中尚不存在的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!