[英]Adding an Event via jQuery to newly created DOM Element
I am trying to assign an event to a newly created DOM Element: 我正在尝试将事件分配给新创建的DOM元素:
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. 执行此代码并单击新创建的div之后,什么也没有发生。 Any idea why? 知道为什么吗?
I have also tried: 我也尝试过:
var Element = document.createElement("div");
$(Element).click(function(event) {
console.log("B");
});
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... 由于您使用的是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 : 这是codepen:
http://codepen.io/anon/pen/xvLqo http://codepen.io/anon/pen/xvLqo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.