简体   繁体   中英

What is the correct way to make new elements with jQuery?

I am wondering what is the correct way to make new elements with jQuery. For example, say that I have a table, into where I want to append some rows according to a list of objects that I have, so the way I do it currently is like so:

var list =
[
    {
        name: 'Banana',
        cost: 100
    },
    {
        name: 'Apple',
        cost: 200
    },
    {
        name: 'Orange',
        cost: 300
    }
];

var appendThis = '';

for(var key in list)
{
    var product = list[key];

    appendThis += '<tr>';
    appendThis += '<td>' + product.name + '</td>';
    appendThis += '<td>' + product.cost + '</td>';
    appendThis += '</tr>';
}

$('#producttable').empty().append(appendThis);

Fiddle: https://jsfiddle.net/ahvonenj/ywjbrrak/

But I have heard that concatenating string and appending the rows like that is a good way to do it and instead I should create tr and td elements, into which I append the data from the list and then append those elements in to the HTML table.

So if that is the seemingly correct way to do it, how exactly is it done? I have only ever created div elements programmatically with $('</div>') , but I am not sure how to create a tr like that and on top of that append the programmatically created td in to the programmatically created tr .

Does it work like this perhaps:

var $row = $('</tr>').append($('<\td>').append('TD CONTENT'));

You can create a new element using the syntax $("<element/>") :

$('#producttable').empty();

for(var key in list)
{
    var product = list[key];

    var $tr = $("<tr/>");
    $tr.append($("<td/>").text(product.name));
    $tr.append($("<td/>").text(product.cost));

    $('#producttable').append($tr);
}

instead of $('</tr>').append($('<\\td>').append('TD CONTENT'));

you should try: $('<tr>').append($('<td>').append('TD CONTENT'));

you don't need to close tags. besides that.. \\t will result in the tab character rather than your desired <td>

you should checkout this question: jQuery document.createElement equivalent?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM