Javascript侦听器到DIV,该DIV将在文档准备就绪后附加
我试图将侦听器放置到一个可滚动的div,如下所示:Javascript侦听器到DIV,该DIV将在文档准备就绪后附加,javascript,jquery,html,listener,document-ready,Javascript,Jquery,Html,Listener,Document Ready,我试图将侦听器放置到一个可滚动的div,如下所示: $(document).ready(function() { $scroll = $('.generic-table') $scroll.scroll(function() { // if($(window).scrollTop() + $(window).height() == $(document).height()) { alert("bottom!");
$(document).ready(function() {
$scroll = $('.generic-table')
$scroll.scroll(function() {
// if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
// }
});
});
问题是该Div不是原始模板的一部分,但在用户执行特定操作后,它被添加到模板
如果Div是在页面的开头加载的,那么它就可以工作了
如何克服这种问题?您不能像@marcelosalloum在评论中正确指出的那样,对
.scroll()
使用事件委派。在实际创建元素时,必须编写处理程序
//Create .generic-table here. BEGIN
Code
//Create .generic-table here. END
//Handle event immediately.
$('.generic-table').scroll(function() {
alert("bottom!");
});
将代码移出.ready并移入添加div的任何位置?只是为了澄清,这是一个事件委派的示例。您正在文档上放置事件以侦听任何滚动事件。然后仅当事件目标为
时才运行回调。根据scroll,泛型表
事件不会通过DOM传播,因此不能将其与委托一起使用。@marcelosalloum-你说得对。不会的。更新我的答案。