简体   繁体   中英

Click event for new DOM element not working

I have this in my js code:

window.onload = function()
{
    document.getElementById('change_user').addEventListener("click", function()
    {
        getUserData(document.getElementById('change_user').getAttribute('data-user'));
    }, false);
}

It works the first time I click the element, but when the element is replaced by the new HTML code, clicking it no longer does anything.

What's wrong?

Once the element is removed, any bound events are also removed. If you re-add the same element later, you'll need to bind the event again.

Perhaps a better approach in this case would be to listen to click events on the body and then check to see if it the target was the change_user element. This is known as event delegation .

See https://davidwalsh.name/event-delegate for plain JS examples.

FYI this is very easy to do with jQuery:

$('body').on('click', '#change_user', function() {…});

See http://api.jquery.com/on/#example-9

When the element is replaced, the event handler is lost. Event handlers are attached to a specific element. When you change the HTML of a parent, all child elements are completely replaced with new elements that start out with no event handlers on them.

You have several choices:

  1. Establish a new event handler on the new element after replacing the element.
  2. Stop replacing the element itself and just modify the contents of the existing element. If the element itself is not replaced, then the event handler will remain intact.
  3. Switch to using delegated event handling from a parent object that is not itself replaced. This relies on the fact that many events bubble up through the parent chain and can be intercepted there, even if child elements come and go or are replaced.

You can read more about delegated event handling in these other answers:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Does jQuery.on() work for elements that are added after the event handler is created?

Should all jquery events be bound to $(document)?

These other answers reference jQuery, but the concept is identical whether using jQuery or using plain Javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM