what does “return this.each()” do in jQuery?

后端 未结 5 989
轮回少年
轮回少年 2021-02-08 21:25

I\'m looking at a jQuery plugin, which has a single function. After setting up the appropriate defaults though a constructor argument the function defines a couple of helper fu

相关标签:
5条回答
  • 2021-02-08 21:36

    this make it possible to keep objects chain, so you can call jquery methods like this:

    $("selector").css().mouseover().etc().blahblah();
    
    0 讨论(0)
  • 2021-02-08 21:44

    .each returns the elements it was called on, so in this case, it is probably to maintain the ability of methods to be chained on that selector. That means that if the plugin'S method is called foo, you should be able to do

    $("mySelector").foo().show();
    

    Because foo returned the result of .each which is basically $("mySelector").

    Hope that made sense.

    0 讨论(0)
  • 2021-02-08 21:49

    It allows for one to call a plugin or an event on a bunch of elements and then apply that same function or event to all of them

    So if you do:

    $('.selector').myPlugin();
    

    And if, let us say, .selector contains 10 elements, all 10 elements would get whatever myPlugin does.


    The reason for returning that .each statement is because .each() returns whatever it was given and it allows you to chain multiple functions and plugins together on one jQuery element.

    For example:

    $('.selector').myPlugin().yourPlugin();
    
    0 讨论(0)
  • 2021-02-08 21:58

    It makes functions chainable

    http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability

    0 讨论(0)
  • 2021-02-08 22:00

    It returns the JQuery object which method is called on as stated in the docs. So you can call another method on the returned value.

    // without method chaining
    myobject.a()
    myobject.b()
    myobject.c()
    
    // with method chaining
    myobject.a().b().c();
    

    See method chaining and fluent interface

    0 讨论(0)
提交回复
热议问题