I have just learned from best practice that is is a lot better to do something like this
var check_icon = $('<i />', {class: 'check icon'});
instead of this
var check_icon = '<i class="check icon"></i>
What I need to do is to create a list of these and I am therefore using each to my data and what to use the check_icon in front of each. Something like this:
var all = '';
$.each(json, function(id, val) {
all += checkicon + val;
});
$('#output').html(all);
My problem is that it does not work. Instead of giving me the HTML code it returns:
[object Object]Carl[object Object]John
I know I can append the data in the $.each
but this is quite CPU intensive and goes against best practices.
I have tried several ways of getting it to work (converting to HTML/string in different ways, but nothing works. I either get [object Object]
or null)
The problem you are having is that you are confusing jQuery objects with HTML strings. It is a little hard to tell what you are trying to do, but here is what I think might work for you.
var output = $("#output");
$.each(json, function(id, val) {
var check_icon = $("<i>").addClass("check icon");
check_icon.html(val);
output.append(check_icon);
});
I just wrote the function which can be use to make all kind of DOM element dynamically
function makeElement(element, options) {
var $element = document.createElement(element);
$.each(options, function (key, value) {
$element.setAttribute(key, value);
});
return $element;
}
and you can invoke it as whenever you required.
var checkIcon = makeElement('i', {class: 'check icon'});
$('parent-container').appendChild(checkIcon);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.