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

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

本文介绍了将参数传递给jQuery的每个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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

你可以调用一个返回函数的函数,该函数接受这两个参数,并在那里存储变量,这些变量将在返回函数由于JavaScript作用域行为而执行。

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.

以下是一个示例:

// 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将由返回的函数引用。您可以使用它来存储任何回调中的变量和访问权限。

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.

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

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

这是关闭的MDN页面,供更多参考

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

这篇关于将参数传递给jQuery的每个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:15