普通JavaScript中的$(document).on()? [英] $(document).on() in plain JavaScript?

查看:127
本文介绍了普通JavaScript中的$(document).on()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中,有 .on()可以用作:

In jQuery there is .on() which can be used as:

$(document).on('click', '.foo', function() { /* ... */ });

这将侦听所有 .foo
但是,它还会侦听以后添加到DOM中的所有最终元素,因此它不等于:

This listens for click events on all DOM elements with the class .foo. However, this also listens for any eventual elements added to the DOM later, so it is not equal to:

var elements = document.getElementsByClassName('foo');
for (var element in elements) {
  element.addEventListener('click', function() { /* ... */ });
}

如何使用普通JavaScript做到这一点?我是否应该使用 MutationObserver ?如果是这样,那又如何?如果不是,那么呢?

How do I do this in plain JavaScript? Am I supposed to use a MutationObserver? If so, then how? If not, then what?

推荐答案

这就是所谓的事件委托,在纯JavaScript中,您可以将click事件附加到父元素然后在单击时检查被单击的元素是否与您要单击的目标匹配并执行所需的操作,如以下示例:

That called event delegation, in the pure javascript you could attach the click event to the parent element then on click check if the clicked element match the target you want to click and perform the action you want ,like the example below :

document.getElementById("parent-item").addEventListener("click", function(e) {
      // e.target is the clicked element!
      // If it was an item with class 'foo'
      if(e.target && e.target.className == "foo") {
         console.log("foo "+e.target.innerText+" was clicked!");
    }
});

希望这会有所帮助。

document.getElementById("parent-item").innerHTML += "<li class='foo'>Item 3</li>";

document.getElementById("parent-item").addEventListener("click", function(e) {
  if(e.target && e.target.className == "foo") {
    console.log("foo "+e.target.innerText+" was clicked!");
  }
});

<ul id="parent-item">
  <li class='foo'>Item 1</li>
  <li class='foo'>Item 2</li>
</ul>

这篇关于普通JavaScript中的$(document).on()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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