jQuery each returns [object Object]

2019-07-21 08:27发布

问题:

My problem is that the html variable returns something like this: [object Object][object Object][object Object][object Object][object Object], instead of the elements.

What should i do different?

var html = '';
$.each(data.response, function(index, value) { 
    var tr = $('<tr>');
    var tr_data = '<td>asd</td>';
    html += tr.data('trackinfo',value).html(tr_data);   
});

$(target).html(html);

回答1:

That's because you're setting the data on the tr and then filling it with your html, but still concatinating an object, which converts it to a string... aka

"[object Object]"

Not exactly sure what you're after but you might try changing this...

html += tr.data('trackinfo',value).html(tr_data);   

To this...

html += tr.data('trackinfo',value).html(tr_data).html();   


回答2:

By default, Jquery creates objects not html mark-up. To get html you should to call html() method.

Here is working code:

var html = '';
$.each(data.response, function(index, value) { 
    var tr = $('<tr>');
    var tr_data = '<td>asd</td>';
    html += tr.data('trackinfo',value).html(tr_data);   
});

$(target).html(html);