Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

jquery - Difference between .on() functions calls

What is the difference between the following?

$(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The difference between these two are

$('.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", ...) 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.

So when to prefer a method

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...