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

标签 javascript jquery html dom

我一直在尝试使用 jQuery 的 .on API 将我的 jQuery 函数应用于动态生成的内容,但它没有按预期工作。该代码的目的是仅当用户将鼠标悬停在 div“.feed_post_full”上时才显示一组选项,而且确实如此。尽管它不适用于动态生成的内容。

这是我的代码:

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

我应该做什么来修复它?

最佳答案

您需要使用 .on() 的委托(delegate)形式才能处理动态创建的元素。您需要此表格:

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

请参阅其他帖子以获取更多说明:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Does jQuery.on() work for elements that are added after the event handler is created?

Does jQuery.on() work for elements that are added after the event handler is created?

您的代码将如下所示:

$(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");

其中父选择器是与动态内容最接近的父选择器,而动态内容本身并不是动态的。

关于javascript - jQuery 函数不适用于动态生成的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22587626/

相关文章:

javascript - 如何在 AJAX JSON 调用后关闭 jQuery 对话框

html - css include url末尾的问号有什么作用?

javascript - 确保浏览器将下载文件而不是打开它

javascript - 如何获取数组中每个dom元素的宽度?

javascript - 找出右键单击的DOM元素

javascript - 在 backbone.js 中使用 jQuery UI 拖放

html - 全宽图像,加载时停止布局更改

javascript - 这有什么问题吗?尝试在我将光标悬停时播放声音,但仅在单击时才有效?

javascript - 带有 Angular JS 变量的 Laravel URL 生成器

javascript - ASP.Net 复选框回发不会触发