简体   繁体   English

jQuery函数不适用于动态生成的内容

[英]jQuery Functions not applying to dynamically generated content

I've been trying to apply my jQuery functions to dynamically generated content by using the .on API from jQuery, but it's not working as it's suppose to. 我一直在尝试通过使用jQuery中的.on API将我的jQuery函数应用于动态生成的内容,但它并没有像它想象的那样工作。 The purpose of the code is to display a set of options only when a user hovers over the div ".feed_post_full", and it does. 代码的目的是仅当用户将鼠标悬停在div“.feed_post_full”上时显示一组选项,并且确实如此。 Although it doesn't apply to content that is dynamically generated. 虽然它不适用于动态生成的内容。

Here is my code here: 这是我的代码:

$(".feed_post_full" ).on({
mouseenter: function() {
    var id = (this.id);
    $('#post_options'+id).show();
}, mouseleave: function() {
    var id = (this.id);
    $('#post_options'+id).hide();
}});

What should I do to fix it? 我该怎么做才能解决这个问题?

You need to use the delegated form of .on() for it to work with dynamically create elements. 您需要使用委托形式的.on()才能使用动态创建元素。 You want this form: 你想要这个表格:

$('#static_parent').on(events, ".dynamic_child", function() {});

See these other posts for more explanation: 有关更多说明,请参阅其他帖子:

jQuery .live() vs .on() method for adding a click event after loading dynamic html jQuery .live()vs .on()方法,用于在加载动态html后添加click事件

Does jQuery.on() work for elements that are added after the event handler is created? jQuery.on()是否适用于在创建事件处理程序后添加的元素?

Does jQuery.on() work for elements that are added after the event handler is created? jQuery.on()是否适用于在创建事件处理程序后添加的元素?

Your code would look like this: 您的代码如下所示:

$(parent selector).on({
    mouseenter: function () {
        var id = (this.id);
        $('#post_options' + id).show();
    },
    mouseleave: function () {
        var id = (this.id);
        $('#post_options' + id).hide();
    }
}, ".feed_post_full");

Where the parent selector is a selector of the closest parent to your dynamic content that is not itself dynamic. 父选择器是动态内容最接近父级的选择器,它本身不是动态的。

Try this: 尝试这个:

$(document).on({
    mouseenter: function() {
    var id = (this.id);
    $('#post_options'+id).show();
}, mouseleave: function() {
    var id = (this.id);
    $('#post_options'+id).hide();
}
}, ".feed_post_full");

Best way to improve performance: 提高性能的最佳方法:

 $("FEED_POST_FULL_PARENT_ELEMENT_AVAILABLE_ON_DOM_READY").on({
        mouseenter: function() {
        var id = (this.id);
        $('#post_options'+id).show();
    }, mouseleave: function() {
        var id = (this.id);
        $('#post_options'+id).hide();
    }
    }, ".feed_post_full");

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

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