.on()函数调用之间的区别 [英] Difference between .on() functions calls
问题描述
以下内容有什么区别?
$(document).on("scroll",".wrapper1", function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$('.wrapper1').on("scroll", function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
何时应准确使用每个功能?
When to should each functions be used exactly?
推荐答案
这两者之间的区别是
$('.wrapper1').on("scroll", ....)
仅将滚动事件绑定到执行该语句时出现的那些元素,即,如果在执行该语句后动态添加任何具有类wrapper1
的新元素,则事件处理程序将不会为这些元素执行.
$('.wrapper1').on("scroll", ....)
binds the scroll event to only those elements which are present at the time of execution of this statement, ie if any new element with class wrapper1
is added dynamically after this statement is executed then the event handler will not get executed for those elements.
$(document).on("scroll",".wrapper1", ...)
将向document
对象注册一个事件处理程序,并且只要在类'wrapper'的元素中发生滚动,就会利用事件冒泡来调用该处理程序,因此它将支持动态添加元素.
$(document).on("scroll",".wrapper1", ...)
on the other hand will register one event handler to the document
object and will make use of event bubbling to invoke the handler whenever scrolling happens within an element with class `wrapper``, so it will support dynamic addition of elements.
那么什么时候首选方法
如果元素数量有限并且没有动态添加元素,则可以选择第一种方法
you can prefer first method if you have only a limited number of elements and they are not dynamically added
如果您有很多元素或者这些元素是动态添加的,那么请选择第二种方法.
Prefer the second method if you have lot of elements or these elements are added dynamically.
这篇关于.on()函数调用之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!