jQuery each()闭包-如何访问外部变量 [英] jQuery each() closure - how to access outside variable
本文介绍了jQuery each()闭包-如何访问外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从$ .each()中访问我的this.rules变量的最佳方法是什么?为什么/如何做的任何解释也会有所帮助!
What's the best way to access my this.rules variable from within $.each()? Any explanation of why/how would also be helpful!
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)
}
推荐答案
存储对this
的引用-例如,在调用.each()
之前将其命名为self
,然后使用访问rules
self.rules
:
Store a reference to this
-- name it self
, for example --, before calling .each()
, and then access rules
using self.rules
:
app.Style = function(node) {
this.style = node;
this.rules = [];
var ruleHolder = node.find('Rule');
var self = this;
$.each(ruleHolder, function(index, value) {
var myRule = new app.Rule($(ruleHolder[index]));
self.rules.push(myRule);
});
console.log(this.rules)
}
这篇关于jQuery each()闭包-如何访问外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文