Tester232323 Tester232323 - 5 months ago 6
jQuery Question

jquery $.each not appending to a string

I am playing around with extend.js and I am running into some issue with jQuery's

$.each
and appending to a string.

var Test = Class.extend(function(){
this.dom = '<div ';
this.class;
this.id;

this.add_class = function(){
this.dom += 'class = "';
$.each(this.class, function(i,e){
console.log(e);
this.dom += e;
this.dom += ' ';
});
this.dom += '"';
return this;
};

this.add_id = function(){
this.dom += 'data-id = "'+this.id+'" ';
return this.dom;
};

});

var tester = new Test();
tester.class = ["coolClass", "TESTER"];
tester.id = "coolId";
console.log(tester.add_class().add_id());


Console shows

coolClass
TESTER
<div class = "" data-id = "coolId"


I just can't see why my class is blank?

Answer

The this value gets reassigned to different things inside a function block. Check out

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

You're going to need to do something like

    var that = this;
    $.each(this.class, function(i,e){
        console.log(e);
        that.dom += e;
        that.dom += ' ';
    });