[英]Passing arguments to jQuery each function
当使用jQuery“each”函数时,有没有办法将参数传递给被调用的函数?
something.each(build);
function build(vars) {
}
我知道我可以简单地执行以下操作,但我想知道是否有一种方法可以直接传递参数。
something.each(function() {
build(vars);
);
您可以使用闭包来完成上述操作。 .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不同。 查看函数如何引用存储的变量并将其附加到文本中
以下是关闭的MDN页面以获取更多参考资料https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.