javascript - Store jQuery object into an Array for later use -


i trying make script creates buttons based on json pass attributes need, this:

var opts = {}; opts.buttons = [{     type: "button",     klass: "btn-default",     text: "no"     }, {     type: "button",     klass: "btn-primary",     text: "yes" }];  var arr = []; var button = $("<button></button>"); _.each(opts.buttons, function (v, k) {     button.prop("type", v.type)         .prop("class", v.klass)         .html(v.text);     arr.push(button); }); 

and then, kind of stringify them, so:

var str = arr.join(''); $('#someel').html(str); 

but not working thought would. return [object object] [object object] instead of button tags.

how can that? nice.

try instead:

opts.buttons = [{     type: "button",     klass: "btn-default",     text: "no"     }, {     type: "button",     klass: "btn-primary",     text: "yes" }];  var arr = []; _.each(opts.buttons, function (v, k) {     var button = $("<button></button>");     button.prop("type", v.type)         .prop("class", v.klass)         .html(v.text);     arr.push(button); }); 

and later...

_.each(arr, function (b) {     $('#someel').append(b); }); 

note 1: opts.buttons not json, object literal.

note 2: $('#someel').html sets html content, i.e. argument should string. can use:

var arr = []; _.each(opts.buttons, function (v, k) {     var button = $("<button></button>");     button.prop("type", v.type)         .prop("class", v.klass)         .html(v.text);     arr.push(button[0].outerhtml); });  var str = arr.join(''); $('#someel').html(str); 

if insist use it.

note 3: [object object] because jquery button elements casted string (because of call of join function), if tostring method of given object not overrided uses default tostring implementation gives [object object] representation.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -