Passing arguments to jQuery each function

14,849

You can accomplish the above using a closure. The .each function takes as an argument a function with two arguments, index and element.

You can call a function that returns a function that takes those two arguments, and store variables in there that will be referenced when the returned function executes because of JavaScript scoping behavior.

Here's an example:

// closureFn returns a function object that .each will call for every object
someCollection.each(closureFn(someVariable));

function closureFn(s){
    var storedVariable = s; // <-- storing the variable here

    return function(index, element){ // This function gets called by the jQuery 
                                     // .each() function and can still access storedVariable

        console.log(storedVariable); // <-- referencing it here
    }
}

Because of how JavaScript scoping works, the storedVariable will be reference-able by the returned function. You can use this to store variables and access in any callback.

I have a jsFiddle that also proves the point. Notice how the text output on the page is different than the HTML defined in the HTML pane. Look at how the function references the stored variable and appends that to the text

http://jsfiddle.net/QDHEN/2/

Here's the MDN page for closures for more reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Share:
14,849

Related videos on Youtube

AncientRo
Author by

AncientRo

Updated on September 15, 2022

Comments

  • AncientRo
    AncientRo over 1 year

    When using the jQuery "each" function, is there a way to pass arguments to the function that is called ?

    something.each(build);
    
    function build(vars) {
    
    }
    

    I know that I can simply do the following, but I was wondering if there is a way in which arguments can be passed directly.

    something.each(function() {
        build(vars);
    );
    
    • Reinstate Monica Cellio
      Reinstate Monica Cellio over 10 years
      I know that I can simply do the following - that is how you do it.