我正在开发一个可以向用户展示调查的应用程序.标记看起来像这样:
<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) 从$ .each()中访问my.rules变量的最佳方法是什么?任何解释为什么/如何也会有所帮助!
app.Style = function(node) {
this.style = node;
this.rules = [];
var ruleHolder = node.find('Rule');
$.each(ruleHolder, function(index, value) {
var myRule = new app.Rule($(ruleHolder[index]));
this.rules.push(myRule);
});
console.log(this.rules)
}
Run Code Online (Sandbox Code Playgroud)