$(document).on() in plain JavaScript?

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-24 22:49:13

问题


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

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

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() { /* ... */ });
}

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


回答1:


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!");
    }
});

Hope this helps.

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>


来源:https://stackoverflow.com/questions/40613527/document-on-in-plain-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!