如何根据滚动条点击调用功能?

时间:2012-01-27 18:06:12

标签: php jquery html

我有Div滚动条。当用户点击滚动条时,我需要根据滚动条点击调用该功能。如何拨打电话?

  1. 我在客户端使用Jquery并在服务器端使用PHP。
  2. 我知道如何进行ajax调用等等。只是在我在div中点击滚动条时需要进行此调用。
  3. 是否可以在该div中为滚动条创建ID。

1 个答案:

答案 0 :(得分:3)

您可以绑定到scroll事件,当用户点击滚动条时不会触发它,但当滚动条因任何原因移动时被触发

//wait for document.ready to fire, meaning the DOM is ready to be manipulated
$(function () {

    //bind an event handler to the `scroll` event for your div element
    $('#my-scroll-div').on('scroll.test-scroll', function () {

        //you can do your AJAX call in here, I would set a flag to only allow it to run once, because the `scroll` event fires A LOT when scrolling occurs
    });
});

请注意,.on()是jQuery 1.7中的新增内容,在这种情况下与使用.bind()相同。

设置我上面建议的标志:

$(function () {

    var AJAX_flag = true;
    $('#my-scroll-div').on('scroll.test-scroll', function () {
        if (AJAX_flag === true) {
            AJAX_flag = false;
            $(this).off('scroll.test-scroll');
            $.ajax({...});
        }
    });
});

更新

将事件处理程序添加到动态创建的元素的最佳解决方案是在将它们添加到DOM之前绑定它们:

function scroll_func () {
    var AJAX_flag = true;
    $(this).on('scroll.test-scroll', function () {
        if (AJAX_flag === true) {
            AJAX_flag = false;
            $(this).off('scroll.test-scroll');//unbind the event handler since we're done with it
            $.ajax({...});
        }
    });
}

$.ajax({
    ...
    success : function (data) {

        //note that this selector will have to change to find the proper elements for you, if you are unsure how to select, start by seeing what data is by doing a `console.log(data);`
        $(data).find('#my-scroll-div').on('scroll', scroll_func).appendTo('#container-element');
    }
});