简体   繁体   English

通过jQuery将事件添加到新创建的DOM元素中

[英]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");
});

You need to add the element to the DOM before it will receive events. 您需要先将元素添加到DOM,然后它才能接收事件。

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.

相关问题 将事件侦听器添加到新添加的DOM元素中 - Adding event listener to a newly added DOM element jQuery 将子元素添加到新创建的元素 - jQuery Adding Child Elements to Newly Created Element 将新创建的dom元素添加到一个空的jQuery对象 - adding newly created dom elements to an empty jQuery object DOM:在onclick事件中删除新创建的“article”元素并使用新创建的删除按钮? - DOM: Delete newly created 'article' element with newly created delete button within onclick event? jQuery .load()在新创建的DOM div元素上不起作用 - jQuery .load() doesn't work on a newly created DOM div element 如何将 jQuery Function 应用于新创建的 DOM 元素? - How can I apply a jQuery Function to a newly created DOM Element? jQuery UI draggable 不适用于新创建的 DOM 元素 - jQuery UI draggable is not working on newly created DOM element 在添加到文档 DOM 之前,如何在动态创建的元素上通过 Jquery 更改 css - How to change css via Jquery on dynamically created element before adding to document DOM jQuery-事件委托仅针对第一个新创建的元素 - jQuery - Event delegation only targeting first newly-created element jQuery:如何将事件附加到类中新创建的元素上 - jQuery: How to attach an event to newly created element inside class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM