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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18911182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:39:07  来源:igfitidea点击:

Passing arguments to jQuery each function

javascriptjqueryeach

提问by AncientRo

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

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

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);
);

回答by migreva

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

您可以使用闭包完成上述操作。的。每个函数采用作为参数有两个参数,索引和元件的功能。

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

您可以调用一个函数,该函数返回一个接受这两个参数的函数,并将变量存储在其中,当返回的函数由于 JavaScript 作用域行为而执行时,这些变量将被引用。

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.

由于 JavaScript 范围的工作方式,storedVariable 将由返回的函数引用。您可以使用它来存储变量并在任何回调中访问。

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

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

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

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

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