将参数传递给jQuery的每个函数

时间:2013-09-20 07:28:10

标签: javascript jquery each

当使用jQuery“each”函数时,有没有办法将参数传递给被调用的函数?

something.each(build);

function build(vars) {

}

我知道我可以简单地执行以下操作,但我想知道是否可以直接传递参数。

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

1 个答案:

答案 0 :(得分:23)

您可以使用闭包来完成上述操作。 .each函数将带有两个参数index和element的函数作为参数。

你可以调用一个返回函数的函数,该函数接受这两个参数,并在那里存储变量,当返回函数由于JavaScript范围执行时将被引用行为。

以下是一个例子:

// 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
    }
}

由于JavaScript作用域的工作原理,storedVariable可以通过返回的函数进行引用。您可以使用它来存储任何回调中的变量和访问权限。

我有一个jsFiddle也证明了这一点。请注意页面上的文本输出与HTML窗格中定义的HTML不同。查看函数如何引用存储的变量并将其附加到文本

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

以下是关闭的MDN页面,以获取更多参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures