使用jQuery检测ajax加载的元素中的滚动 [英] Detect scroll in an ajax loaded element with jQuery

查看:77
本文介绍了使用jQuery检测ajax加载的元素中的滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个加载了ajax的按钮,并且您需要监听它的点击,请像下面这样使用.on():

If there's a button that is loaded with ajax, and you need to listen clicks on it, use the .on() like so:

$(document).on('click', '.button', function(e) {
    // Do somethinh...
});

我知道,但是我不能在滚动中使用相同的逻辑.我有一个名为#overlayer的元素,该元素会加载ajax,然后尝试监听其上的滚动并触发一个函数,该函数将在要退出视口时在侧边栏添加粘性类:

That I know, but I can't use this same logic with a scroll. I got an element called #overlayer that gets ajax loading in, then I'm trying to listen scroll on it and trigger a function that adds sticky class to sidebar when it's about to exit the viewport:

$(document).on('scroll', '#overlayer', function() {
    stickySidebar();
    console.log('scroll happened');
});

但是它不起作用.

我可以使它像这样工作:

I can get it to work like this:

$('#overlayer').on('scroll', function() {
    stickySidebar();
    console.log('scroll happened');
});

但是它不能在ajax加载的内容上工作.

But it wont work on the ajax loaded content.

推荐答案

除非将事件插入到DOM中,例如将事件绑定到ajax加载的元素,否则将无法将其绑定.在回调函数中.假设您正在使用$.post,请执行以下操作:

Binding an event to an ajax loaded element won't work unless you do it after the element has been inserted into the DOM, e.g. in the callback function. Assuming you're using $.post, do something like this:

$.post("filename", function(data){

    //insert element here

    //event handler
    $('#overlayer').on('scroll', function() {
        stickySidebar();
        console.log('scroll happened');
   });
})

这篇关于使用jQuery检测ajax加载的元素中的滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆