简体   繁体   English

动态生成的元素在jQuery中动态生成的元素中的事件绑定

[英]Event binding for a dynamically generated element within a dynamically generated element in jQuery

I'm trying to use 'click' on a dynamically generated DOM. 我正在尝试在动态生成的DOM上使用“click”。 I know that I can just use live or on, however my dynamically generated content is within multiple dynamically generated pieces of content and live/on no longer works. 我知道我可以使用live或on,但是我动态生成的内容在多个动态生成的内容中,并且live / on不再有效。

So my code looks something like this but with more elements before El_b: 所以我的代码看起来像这样,但在El_b之前有更多的元素:

El_a = document.createElement("li");
El_b = document.createElement("a");
El_b.id = "myEl";
El_a.appendChild(El_b);

Is there a way to make this work? 有没有办法让这项工作?

PS: I've also tried the livequery jQuery plugin. PS:我也尝试过livequery jQuery插件。

As far as delegation is concerned, you always have at least one static DOM element available to you, which is the document . 就委托而言,您始终可以使用至少一个静态DOM元素,即document If you can't find a closer element to delegate to, delegate to this. 如果找不到要委托的更接近的元素,请委托给它。

However, delegation seems to be unnecessary here. 但是,这里似乎没有必要进行授权。 The entire process of creating your elements and attaching listeners could be condensed to: 创建元素和附加侦听器的整个过程可以简化为:

var a = $("<li/>").append($("<a/>").attr("id", "myElement")).click(function () {
    alert('hello');
});

If, as you say, you cannot change the object creation, you can still select it by its ID and attach the listener: 如果,如您所说,您无法更改对象创建,您仍然可以通过其ID选择它并附加侦听器:

$('#myElement').click(function () {
    alert('hello');
});

Also, those are document fragments , not documents proper, and certainly not DOMs. 此外,这些是文档片段 ,而不是正确的文档,当然也不是DOM。

If you want to bind a function on the click event on El_b, you can just do this : 如果要在El_b上的click事件上绑定函数,可以这样做:

$(El_b).click(function() {
    // Your code here
});

But you can use on i think. 但是你可以使用on ,我认为。 Even if you create multiple DOM elements. 即使您创建多个DOM元素。 You can use the document or the body . 您可以使用documentbody Example : 示例:

$('body').on('click', 'li a.my_class', function() {
    // Your code here
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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