当使用jQuery“每个”函数时,是否有一种方法将参数传递给被调用的函数?
something.each(build);
function build(vars) {
}
我知道我可以简单地执行以下操作,但我想知道是否有一种方法可以直接传递参数。
something.each(function() {
build(vars);
);
发布于 2014-04-29 06:38:09
您可以使用闭包来完成上述操作。.each函数将带有两个参数(索引和元素)的函数作为参数。
您可以调用一个函数,该函数返回一个接受这两个参数的函数,并将变量存储在其中,当返回的函数由于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
https://stackoverflow.com/questions/18911182
复制相似问题