我有带滚动条的div。当用户点击滚动条时,我需要调用基于滚动条点击的功能。我该怎么打电话?
- 我在客户端使用Jquery,在服务器端使用PHP
- 我知道如何进行ajax调用等等。我只想当在div中点击滚动条时,我需要进行这个调用
是否可以在该分区中制作滚动条的ID。
您可以绑定到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');
}
});