简体   繁体   中英

Adding an Event via jQuery to newly created DOM Element

I am trying to assign an event to a newly created DOM Element:

var Element = document.createElement("div");
$(document).on('click',Element,function() {
    console.log("B");
});

After executing this code and clicking on the newly created div, nothing happens. Any idea why?

I have also tried:

var Element = document.createElement("div");
$(Element).click(function(event) {
    console.log("B");
});

You need to add the element to the DOM before it will receive events.

Here's one way to do it:

var $div = $('<div>')
  .text('Click Me!')
  .on('click', function() {
    alert('Clicked!');
  });

$(document.body).append($div);

// Now you can click on it and see the alert.

Since you're using jQuery...

var Element = $("<div/>").click(function() {console.log("B");}).appendTo('body');

Of course, append it where you need it...

Just bind your event on the body and pass your selector in parameter like this:

$('body').on('click','.foo',function() {
    console.log("B");
});

var Element = document.createElement("div").className = "foo";

Here the codepen :

http://codepen.io/anon/pen/xvLqo

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