简体   繁体   中英

How to attach events to new added html elements

If I had a function like this:

document.someElement.click = function(){alert(555);}

and I don't have in the element someElement in the HTML page itself, so after I add someElement to the page, but the code before doesn't work.

What is the best way to add event listeners to (new) dynamically added HTML elements?

There are two common strategies here.

  1. Hook the event on the element after you add the element to the DOM.

  2. Use event delegation .

The first is fairly straightforward, so I'll focus on the second:

The idea with event delegation is that most DOM events "bubble" from the element where they occur up to the document, and you can handle them at any level.

So for instance, suppose you have

<div id="container">
</div>

You can hook the click event on the container div, and then if you do something like this:

var span = document.createElement('span');
span.innerHTML = "Hi there";
document.getElementById("container").appendChild(span);

...then, when you click the span , the event will bubble up to the container, and you see the click in the container's click handler.

You can tell which element started the event by using the target property on the event object.

Here's an example:

HTML:

<button id="theButton">Click To Add</button>
<div id="container"></div>

JavaScript:

// Note that this code is at the end of the document
(function() {
  var container = document.getElementById("container");

  // Hook clicks on the button
  document.getElementById("theButton").onclick = buttonClick;

  // Hook clicks on the container
  container.onclick = containerClick;

  // Handle button clicks
  function buttonClick() {
    var child = document.createElement('div');
    child.id = ('d' + container.childNodes.length) +
      Math.floor(Math.random() * 10000);
    child.innerHTML = "I'm child div '" + child.id + "'";
    container.appendChild(child);
  }

  // Handle container clicks
  function containerClick(event) {
    event = event || window.event;

    alert("You clicked child '" + event.target.id + "'");
  }

})();

Live Example | Source

Note: I've used onclick to keep things simple. In production, I recommend using addEventListener (or attachEvent on IE). In fact, I typically recommend using a good library like jQuery , YUI , Closure , or any of several others for the significant utility functionality they provide (including smoothing over the addEventListener / attachEvent thing).

You can use addEventListener() ( attachEvent() for IE) to register a click handler on a newly created element, for example:

var x = document.createElement('div');
x.innerText = 'click me';

x.addEventListener('click', function() {
  alert('i am clicked');
});

document.body.appendChild(x);

Demo

Update

Do take a look at TJ's answer ; he's basically saying that you can set up a container onto which you define a click handler; any elements that are added inside will have their events bubble up to the container. This way you only need one click handler and not one per element.

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