add event listener on elements created dynamically

2019-01-01 08:45发布

Is possible to add event listener (javascript) to all dynamically generated elements? I'm not the owner of the page, so I cannot add a listener in a static way.

for all the elements created when the page loaded I use:

doc.body.addEventListener('click', function(e){
//my code
},true);

I need a method to call this code when new elements appear on the page, but I cannot use jQuery (delegate, on, etc cannot work in my project). How can i do this?

5条回答
永恒的永恒
2楼-- · 2019-01-01 09:21

It sounds like you need to pursue a delegation strategy without falling back to a library. I've posted some sample code in a Fiddle here: http://jsfiddle.net/founddrama/ggMUn/

The gist of it is to use the target on the event object to look for the elements you're interested in, and respond accordingly. Something like:

document.querySelector('body').addEventListener('click', function(event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    // do your action on your 'li' or whatever it is you're listening for
  }
});

CAVEATS! The example Fiddle only includes code for the standards-compliant browsers (i.e., IE9+, and pretty much every version of everyone else) If you need to support "old IE's" attachEvent, then you'll want to also provide your own custom wrapper around the proper native functions. (There are lots of good discussions out there about this; I like the solution Nicholas Zakas provides in his book Professional JavaScript for Web Developers.)

查看更多
呛了眼睛熬了心
3楼-- · 2019-01-01 09:24

I have created a small function to add dynamic event listeners, similar to jQuery.on().

It uses the same idea as the accepted answer, only that it uses the Element.matches() method to check if the target matches the given selector string.

addDynamicEventListener(document.body, 'click', '.myClass, li', function (e) {
    console.log('Clicked', e.target.innerText);
});

You can get if from github.

查看更多
忆尘夕之涩
4楼-- · 2019-01-01 09:33

Delegating the anonymous task to dynamically created HTML elements with event.target.classList.contains('someClass')

  1. returns true or false
  2. eg. let myEvnt = document.createElement('span'); myEvnt.setAttribute('class', 'someClass'); myEvnt.addEventListener('click', e => { if(event.target.classList.contains('someClass')){ console.log(${event.currentTarget.classList })}})

  3. Reference: https://gomakethings.com/attaching-multiple-elements-to-a-single-event-listener-in-vanilla-js/

  4. Good Read: https://eloquentjavascript.net/15_event.html#h_NEhx0cDpml
  5. MDN : https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets
  6. Insertion Points:
查看更多
低头抚发
5楼-- · 2019-01-01 09:33

Use classList property to bind more than one class at a time

var container = document.getElementById("table");
container.classList.add("row", "oddrow", "firstrow");
查看更多
人气声优
6楼-- · 2019-01-01 09:37

Depends on how you add new elements.

If you add using createElement, you can try this:

var btn = document.createElement("button");
btn.addEventListener('click', masterEventHandler, false);
document.body.appendChild(btn);

Then you can use masterEventHandler() to handle all clicks.

查看更多
登录 后发表回答