最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - $(document).on() in plain JavaScript? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Nov 15, 2016 at 15:34 Zakaria Acharki 67.5k15 gold badges78 silver badges105 bronze badges asked Nov 15, 2016 at 15:21 FredFred 12.8k7 gold badges64 silver badges90 bronze badges 1
  • Without looking at the jquery source (which is "plain JavaScript"), I suspect it adds a listener to document then uses sizzle to check that the event source matches the selector. – fdomn-m Commented Nov 15, 2016 at 15:30
Add a comment  | 

1 Answer 1

Reset to default 14

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>

发布评论

评论列表(0)

  1. 暂无评论