纯javascript等价于带有选择器的$(document).on(event)
Plain javascript equivalent of $(document).on(event) with selector
我正在尝试将jQuery事件处理程序转换为纯javascript。页面上加载了一个特定的选择器,因此设计该选择器时只有一个事件目标文档:
$(document).on("click", selectorString, function(event) {
// do stuff
});
其中,selector
是作为字符串".one, .two, .three
"的选择器列表。
我很难在没有jQuery的情况下复制它:
document.addEventListener("click", function(event){
if (elementHasClass(event.target, selectorString) {
// do stuff
}
});
但这并没有达到所需的行为,因为监听器只在document
元素上,而不是在文档中的选定元素上。有人能帮忙吗?
您的问题似乎是它不适用于嵌套元素。
例如,如果您单击一个嵌套的span
元素,该元素具有指定类的父级,则它不起作用,因为您只是在检查span
元素(即event.target
)是否具有该类。
为了解决这个问题,您可以委托事件,并检查event.target
元素的父元素中是否有指定的类:
此处示例
document.addEventListener("click", function (e) {
var target = e.target;
while (target && target.parentNode !== document) {
target = target.parentNode;
if (!target) { return; } // If element doesn't exist
if (target.classList.contains('target')){
// do stuff
console.log(e.target);
}
}
});
相关文章:
- jQuery(document).on('click.classname'.......)?
- 对于jqGrid:在keypress事件中调用$(document).on('click'.)无法正常工
- Javascript on click事件在函数中不起作用,但在document.ready()中起作用
- $(document).on('focus'或$(document).bind('input
- $(document).on('click') 和 $('p[class=“classname”
- AngularJS:$scope.$on 和 document.addEventListener 之间的差异
- document.execCommand('copy') on objects not in DOM?
- $(document).on('click', selector, function() ) 与 :no
- 如果不对 .off() 使用相同的 $(document) 绑定,则无法删除使用 .on() 绑定到 $(documen
- 为什么$document.on('keydown')晚了一个
- 选择使用“;这个“;关键字使用document.on(.)-Jquery
- $(document).on() in plain JavaScript?
- 单元测试$(document).on
- jQuery $(document).on()工作不正常
- 如何使用jQuery声明document.on()侦听器来更改特定选定元素的文本
- document.addEventListener vs. $(document).on
- $document.on('click')中的更改没有反映在视图中
- jQuery(document).on ('focus')?
- document.on('event')和$().event的区别
- $(document).on("click",".class_name",fun