2011-02-17 90 views
35

我正在开发一个应用程序,它将向用户展示调查。该标记看起来是这样的:将附加参数传递给jQuery each()回调

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

我想从使用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); 
} 

回答

29

在对问题进行迭代之前,您应该能够创建对您的调查的参考。

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

工作jsfiddle

+1

谢谢! +1为[jsfiddle.net](http://www.jsfiddle.net) – MarioVW 2011-02-17 20:19:50

15

虽然这个例子可能不相关的答案,但因为这个问题是如何参数每个功能传递给jQuery的。

第一种方法:使用部分功能 - more on thisclosure library

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

第二种方法是

$。每个函数可以接受或者2个参数IndexElement (也可称为this) OR 如果你不需要Index那么你可以传递Array作为参数传递给$。每次和元件作为本

警告称: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); 
}, 

它将调用each: function(obj, callback, args)

然后调用callback.apply(obj[ i ], args);如果你通过数组作为参数 OTH erwise 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']); 

仅供参考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; 
    }, 
+1

这个答案是对问题中提出的问题进行更彻底的讨论。 – axlotl 2015-12-07 22:34:56

7

我遇到了类似的问题。通过参数去的每一个功能:

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

为我工作。只是想强调,参数应该始终是类型数组。如果参数是其他类型,则不工作。 – 2016-09-07 11:24:00

1

//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>