How to handle events for elements added by javascript ? without .on() jQuery? [closed]

StackOverflow https://stackoverflow.com/questions/21538302

  •  06-10-2022
  •  | 
  •  

문제

I've read alot of answers about my question but they are all about using .on() of jQuery, I'm in the process of learning Javascript, I wanna know how to handle events of newly created elements by JavaScript.

I've tried using addEventListener it's fired in the proccess of adding the element to the DOM, and not when the event occures!

도움이 되었습니까?

해결책 2

Be sure you pass a reference to the event handler instead of calling it when you set it up. In other words, do this:

var handler = function(ev) { /* ... */ };

el.addEventListener("click", handler);

But don't do this:

var handler = function(ev) { /* ... */ };

el.addEventListener("click", handler());

다른 팁

The fundamental thing is to hook the event on a container that you'll be adding the elements to. Most events bubble, and so (for instance) a click on a child element bubbles up to the parent element.

So say you have:

<ul id="container"></ul>

and you do this:

document.getElementById("container").addEventListener("click", function(e) {
    console.log(e.target.innerHTML);
});
setInterval(function() {
    var li = document.createElement('li');
    li.innerHTML = "Added " + new Date();
    document.getElementById("container").appendChild(li);
}, 2000);

Now we have new lis being added every couple of seconds. Clicking the list item will show its contents, because the click bubbles to the parent container, which is where we've hooked the click. e.target is a reference to the element where the event originated.

This is called event delegation.

Live Example | Source

If you have elements within the child elements, you may have to look at e.target.parentNode or e.target.parentNode.parentNode, etc., to find the one you care about. (This usually involves a loop, going to each parent node in turn, stopping when you've reached the element on which you hooked the event.)


Side note: Using jQuery is using JavaScript (unless you use CoffeeScript, TypeScript, Dart, or some other language). jQuery is a library, not a language.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top