Javascript 将附加参数传递给 jQuery each() 回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5033861/
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-08-23 15:21:21  来源:igfitidea点击:

Pass additional parameters to jQuery each() callback

javascriptjqueryoop

提问by MarioVW

I'm working on an app that will present surveys to the user. The markup looks something like this:

我正在开发一个应用程序,它将向用户呈现调查。标记如下所示:

<body>
    <div class="question" id="q1">
        Question 1
    </div>
    <div class="question" id="q2">
        Question 2
    </div>
    <!-- etc -->
</body>

I want to construct the JavaScript objects from the DOM using jQuery, so in the Surveyconstructor I'm traversing the jQuery set using the each()method. The problem is that within the callback function I'm unable to get a reference to the Surveyobject in order to append each Questionobject to the Survey.questionsarray. How can get a reference to the Surveyobject? Is there a way to pass an additional parameter (e.g. a reference to the Surveyobject) to the callback function?

我想使用 jQuery 从 DOM 构造 JavaScript 对象,因此在Survey构造函数中,我使用each()方法遍历 jQuery 集。问题是,在回调函数中,我无法获得对Survey对象的引用,以便将每个Question对象附加到Survey.questions数组中。如何获得对Survey对象的引用?有没有办法将附加参数(例如对Survey对象的引用)传递给回调函数?

function Survey() {
    this.questions = new Array;
    $('.question').each(function(i) { (/* Survey object */).questions.push(new Question(this)); });
}

function Question(element) {
    this.element = $(element);
}

采纳答案by Mark Coleman

You should be able to create a reference to your survey before you iterate over the questions.

在迭代问题之前,您应该能够创建对调查的引用。

function Survey() {
    this.questions = new Array();
    var survey = this;
    $('.question').each(function(i) {
        survey.questions.push(new Question(this));
    });
}

function Question(element) {
    this.element = $(element);
}

var survey = new Survey();

$.each(survey.questions, function() {
    $("ul").append("<li>" + this.element.text() + "</li>");
});

Working example on jsfiddle

jsfiddle 上的工作示例

回答by dekdev

Though this may not be relevant answer , But since the question is how to pass parameter to jQuery each function .

虽然这可能不是相关的答案,但由于问题是如何将参数传递给 jQuery 每个函数。

First Approach : Using Partial Function- more on thisand from closure library

第一种方法:使用偏函数-更多关于这个和来自闭包库的信息

jsfiddle:

jsfiddle

var param = 'extra-param';   

var partial = function(fn, var_args) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function() {
    // Clone the array (with slice()) and append additional arguments
    // to the existing arguments.
    var newArgs = args.slice();
    newArgs.push.apply(newArgs, arguments);
    return fn.apply(this, newArgs);
  };
};

$(['joe','james','rick','kirk']).each(partial (function (index,value) {
    alert(arguments.length);
    alert(arguments[0]);
 },param));

Second Approach is

第二种方法是

$.each function can take either 2 parameters Indexand Element(which can also be referred as this) OR if you do not need Indexthen you can pass Arrayas argument to $.each and element can referred as this

$.each 函数可以采用 2 个参数IndexElement(也可以称为this),或者如果您不需要,Index则可以将其Array作为参数传递给 $.each 并且元素可以称为 this

CAUTION : args is for internal use only - by jQuery

注意:args 仅供内部使用 - 由 jQuery

// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
    return jQuery.each( this, callback, args );
},

Which will call each: function( obj, callback, args )

哪个会调用 each: function( obj, callback, args )

then call callback.apply( obj[ i ], args );if you pass array as argument otherwise callback.call( obj[ i ], i, obj[ i ] );

callback.apply( obj[ i ], args );如果您将数组作为参数传递,则调用,否则调用 callback.call( obj[ i ], i, obj[ i ] )

please note the difference of apply and call

请注意apply和call的区别

Sample code : http://jsfiddle.net/dekajp/yA89R/1/

示例代码:http: //jsfiddle.net/dekajp/yA89R/1/

var param = 'rick';
$(['joe','james','rick','kirk']).each(function (arg1 , arg2 ,arg3) {
    //alert('[this: '+this +'] [arg1: '+ arg1 +'] [arg2:'+arg2+'] [param:'+param+']');
},['hello 1','hello 2','hello 3']);

For Reference jQuery Each Code version 1.9

供参考 jQuery Each Code 1.9 版

// args is for internal usage only
    each: function( obj, callback, args ) {
        var value,
            i = 0,
            length = obj.length,
            isArray = isArraylike( obj );

        if ( args ) {
            if ( isArray ) {
                for ( ; i < length; i++ ) {
                    value = callback.apply( obj[ i ], args );

                    if ( value === false ) {
                        break;
                    }
                }
            } else {
                for ( i in obj ) {
                    value = callback.apply( obj[ i ], args );

                    if ( value === false ) {
                        break;
                    }
                }
            }

        // A special, fast, case for the most common use of each
        } else {
            if ( isArray ) {
                for ( ; i < length; i++ ) {
                    value = callback.call( obj[ i ], i, obj[ i ] );

                    if ( value === false ) {
                        break;
                    }
                }
            } else {
                for ( i in obj ) {
                    value = callback.call( obj[ i ], i, obj[ i ] );

                    if ( value === false ) {
                        break;
                    }
                }
            }
        }

        return obj;
    },

回答by Olivier Royo

I encountered a similar issue. to pass param to an each function:

我遇到了类似的问题。将参数传递给 each 函数:

var param1 = "one";
var param2 = "two";

var params = [ param1, param2 ];


$( '#myTable > tbody  > tr' ).each(function( index ) {

     var param1back = params[0];
     var param2back = params[1];

},params);

回答by TheDarkIn1978

//Create extra data
var dataArray = ["A", "B", "C"];

//Send default arguments from jQuery's each (index and item) along
//with our new data argument to a named function handler.
$("#myList").children().each(function(jqIndex, jqItem)
                            {
                              listItemsHandler(jqIndex, jqItem, dataArray[jqIndex]);
                            });    

//Named function handler accepting 3 arguments.
function listItemsHandler(index, item, data)
{
    console.log(index + " " + item + " " + data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ol id = "myList">
  <li>First</li>
  <li>Second</li>
  <li>Third</li> 
</ol>