2011-02-17 88 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>

相關問題