scroll()在jQuery中不适用于动态元素 [英] scroll() in not working in jQuery for dynamic elements
问题描述
我正在使用以下代码.这不适用于动态创建的元素.我使用的是jQuery 1.4.2
I am using the following.This is not working for dynamically created elements.I am usinh jQuery 1.4.2
$(".wrapper1").live("scroll",function(){
alert(123);
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
这也不适用于普通元素.(页面加载时会加载哪个页面)
This is also not working for normal elements also.(Which are loaded while the page loading)
这可能是什么原因.请帮助我.谢谢....
What might be the reason here .Please help me.Thanks in advance....
推荐答案
浏览器发生了变化,jQuery的错误已修复,这就是始终使用最新版本的jQuery非常重要的两个原因(经过适当的测试后,您不能仅仅指出到最新).
Browsers change, jQuery bugs are fixed, that's two reasons why it's important to always use a recent version of jQuery (after due tests, you can't just point to latest).
对于另一种事件类型,适用于jQuery 1.9的代码将是
Your code, adapted to jQuery 1.9, would be, for another event type,
$(document).on("event_type",".wrapper1", function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
之所以使用$(document)
作为接收者而不是$(".wrapper1")
,是因为只有绑定时存在的元素才可以接收和委托事件. on
不能像旧的live
一样工作.
The reason to use $(document)
as receiver and not $(".wrapper1")
is that only the elements existing at binding time would receive and delegate the events. on
doesn't work like the old live
.
除了这不适用于scroll
事件,因为它们不会冒泡.
Except that this won't work for scroll
events as they don't bubble.
所以我可以提出的最合理的解决方案是定义一个函数:
So the most reasonnable solution I can propose would be to define a function :
$.fn.bindScrollHandler1 = function(){
$(this).on('scroll', function(){
$(".wrapper2").scrollLeft($(".wrapper1").scrollLeft());
});
}
并在开始时调用它:
$('.wrapper1').bindScrollHandler1();
,并且每次创建新的.wrapper1元素时:
and each time you create a new .wrapper1 element :
myNewElement.bindScrollHandler1();
请注意,您似乎缺少一些完整的逻辑,因为您没有配对滚动条,而是使它们全部工作相同.
Note that your complete logic seems a little lacking, as you don't pair the scrollbars but make them all work the same.
这篇关于scroll()在jQuery中不适用于动态元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!