将其他参数传递给jQuery each()回调

Mar*_*oVW 38 javascript oop jquery

我正在开发一个可以向用户展示调查的应用程序.标记看起来像这样:

<body>
    <div class="question" id="q1">
        Question 1
    </div>
    <div class="question" id="q2">
        Question 2
    </div>
    <!-- etc -->
</body>
Run Code Online (Sandbox Code Playgroud)

我想从使用jQuery的DOM构建JavaScript对象,所以在Survey构造函数中,我穿越了jQuery使用设置each()方法.问题是在回调函数中我无法获得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);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*man 33

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

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>");
});
Run Code Online (Sandbox Code Playgroud)

关于jsfiddle的工作示例


dek*_*dev 18

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

第一种方法:使用部分函数 - 更多关于此关闭库

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));
Run Code Online (Sandbox Code Playgroud)

第二种方法是

$ .each函数可以采用2个参数IndexElement(也可以称为this)OR或者如果你不需要Index那么你可以将Array参数作为参数传递给$ .each并且元素可以作为这个引用

注意: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 );
},
Run Code Online (Sandbox Code Playgroud)

哪个会打电话 each: function( obj, callback, args )

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

请注意申请和电话的区别

示例代码: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']);
Run Code Online (Sandbox Code Playgroud)

参考jQuery每个代码版本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;
    },
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是对问题中提出的问题进行更彻底的讨论. (3认同)

Oli*_*oyo 10

我遇到了类似的问题.将param传递给每个函数:

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);
Run Code Online (Sandbox Code Playgroud)

  • 这应该是一个可以接受的答案,因为实际上这是使用诸如“ each”之类的方法设计jQuery参数的方式。其他答案只是使事情复杂化。 (2认同)
  • 这不应该是公认的答案。我们可以将变量添加到我们想要的全局范围中,但这只会污染全局空间......这不是好的编码!我认为OP问的是如何将实例变量传递到.each()中,该变量不会在全局级别定义,因此需要传入。 (2认同)