将其他参数传递给jQuery each()回调 [英] Pass additional parameters to jQuery each() callback
问题描述
我正在开发一款可向用户展示调查问题的应用。标记看起来像这样:
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>
我想使用jQuery从DOM构造JavaScript对象,所以在 Survey
构造函数我正在使用 each()
方法遍历jQuery集。问题是在回调函数中我无法获得对 Survey
对象的引用,以便附加每个问题
对象 Survey.questions
数组。如何获得对 Survey
对象的引用?有没有办法将附加参数(例如对 Survey
对象的引用)传递给回调函数?
I want to construct the JavaScript objects from the DOM using jQuery, so in the Survey
constructor 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 Survey
object in order to append each Question
object to the Survey.questions
array. How can get a reference to the Survey
object? Is there a way to pass an additional parameter (e.g. a reference to the Survey
object) to the callback function?
function Survey() {
this.questions = new Array;
$('.question').each(function(i) { (/* Survey object */).questions.push(new Question(this)); });
}
function Question(element) {
this.element = $(element);
}
推荐答案
你应该能够创造在迭代问题之前参考您的调查。
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>");
});
这篇关于将其他参数传递给jQuery each()回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!