Attach scroll event to div with body on() binding fails

左心房为你撑大大i 提交于 2020-02-01 12:17:05

问题


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.

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?


回答1:


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:

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/

$('#link').click(function(){

    //dynamically created element
    $('body').append('<div class="demo"></div>');

    //dynamically added event
    $('.demo').on('scroll', function () {
        alert('scrolling');
    });

});



回答2:


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:

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
);


来源:https://stackoverflow.com/questions/19027378/attach-scroll-event-to-div-with-body-on-binding-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!