jQuery each() closure - how to access outside variable

前端 未结 3 1145
时光取名叫无心
时光取名叫无心 2021-02-05 07:44

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) {
    th         


        
3条回答
  •  后悔当初
    2021-02-05 08:07

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

提交回复
热议问题