jQuery 将滚动事件附加到带有主体 on() 绑定的 div 失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19027378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attach scroll event to div with body on() binding fails
提问by Jompis
I'm having some trouble with the scroll event.
我在滚动事件方面遇到了一些麻烦。
I'm trying to attach/bind the event to a specific div,
and I'm using $('body').on()
to do it, due to the fact that
the content is reloaded when sorting, so it will lose its binding.
我正在尝试将事件附加/绑定到特定的 div,并且我正在使用$('body').on()
它,因为排序时内容会重新加载,因此它将失去其绑定。
This doesn't work, the event is not fired:
这不起作用,事件不会被触发:
$('body').on('scroll', 'div.dxgvHSDC + div', function () {
}
This on the other hand works:
另一方面,这有效:
$('body').on('mousewheel DOMMouseScroll', 'div.dxgvHSDC + div', function () {
}
And this as well:
这也是:
$('div.dxgvHSDC + div').on('scroll', function () {
}
What's the problem?
有什么问题?
回答by Alvaro
You can not add delegation to the scroll
event. This event doesn't bubble up the DOM and therefore you can not delegate it to any element. You can find more information here:
您不能向scroll
事件添加委托。此事件不会使 DOM 冒泡,因此您不能将其委托给任何元素。您可以在此处找到更多信息:
The scroll event does not bubble up.
Although the event does not bubble, browsers fire a scroll event on both document and window when the user scrolls the entire page.
滚动事件不会冒泡。
虽然事件不会冒泡,但当用户滚动整个页面时,浏览器会在文档和窗口上触发滚动事件。
You will need to create the event handler inside the event which creates your scrolling element.
您需要在创建滚动元素的事件中创建事件处理程序。
Living example: http://jsfiddle.net/Um5ZT/1/
活生生的例子:http: //jsfiddle.net/Um5ZT/1/
$('#link').click(function(){
//dynamically created element
$('body').append('<div class="demo"></div>');
//dynamically added event
$('.demo').on('scroll', function () {
alert('scrolling');
});
});
回答by A. Wolff
On modern browsers (IE>8), you can capture scroll
event to e.g document
level for dynamic element. As jQuery doesn't implement capturing phase, you have to use javascript addEventListener()
method:
在现代浏览器 (IE>8) 上,您可以将scroll
事件捕获到例如document
动态元素的级别。由于 jQuery 没有实现捕获阶段,你必须使用 javascriptaddEventListener()
方法:
document.addEventListener(
'scroll',
function(event){
var $elm = $(event.target);
if( $elm.is('div.dxgvHSDC + div')){ // or any other filtering condition
// do some stuff
console.log('scrolling');
}
},
true // Capture event
);