Jquery .on('scroll') 在滚动时不触发事件 [英] Jquery .on('scroll') not firing the event while scrolling

查看:47
本文介绍了Jquery .on('scroll') 在滚动时不触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

滚动 ul 时不会触发 Scroll 事件.我使用的是 jQuery 1.10.2 版.当我从 ajax 页面加载 ul 时,我不能使用 $('ulId').on('scroll', function() {}); 或其他实时方法.请帮我找到解决办法.

Scroll event is not firing while scrolling the ul. I'm using jQuery version 1.10.2. As I'm loading the ul from an ajax page, I couldn't use $('ulId').on('scroll', function() {}); or other live methods. Please help me to find a solution.

$(document).on( 'scroll', '#ulId', function(){
    console.log('Event Fired');
});

推荐答案

你可能忘记在 id 选择器的 id 之前给 #,你需要在 # 之前给 #code>id 即是 ulId

You probably forgot to give # before id for id selector, you need to give # before id ie is ulId

$(document).on( 'scroll', '#idOfDivThatContainsULandScroll', function(){
    console.log('Event Fired');
});

编辑

以上不起作用,因为滚动事件不会在用于事件委托的 DOM 中冒泡,请参阅此问题 为什么不委派滚动工作.

The above would not work because the scroll event does not bubble up in DOM which is used for event delegation, see this question why doesn't delegate work for scrolling.

但是对于现代浏览器 >IE 8,你可以用另一种方式.除了使用 jquery 进行委托,您还可以使用 javascript document.addEventListener 使用事件捕获来完成,第三个参数为 true;在本教程中了解冒泡和捕获的工作原理.

But with modern browsers > IE 8, you can do it in another way. Instead of delegating by using jquery, you can do it using event capturing with javascript document.addEventListener, with the third argument as true; see how bubbling and capturing work in this tuturial.

现场演示

document.addEventListener('scroll', function (event) {
    if (event.target.id === 'idOfUl') { // or any other filtering condition        
        console.log('scrolling', event.target);
    }
}, true /*Capture event*/);

如果您不需要事件委托,那么您可以将滚动事件直接绑定到 ul,而不是通过 document 委托.

If you do not need event delegation then you can bind scroll event directly to the ul instead of delegating it through document.

现场演示

$("#idOfUl").on( 'scroll', function(){
   console.log('Event Fired');
});

这篇关于Jquery .on('scroll') 在滚动时不触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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