Display JavaScript Object in HTML

后端 未结 4 1132
予麋鹿
予麋鹿 2021-01-06 08:28

I have a object that looks like this:

var grocery_list = {
  \"Banana\": { category: \"produce\", price: 5.99 },
  \"Chocolate\": { category: \"candy\", pric         


        
4条回答
  •  情书的邮戳
    2021-01-06 08:49

    You can create HTML elements with jQuery: $('

    ', {attr1: value, attr2: value}); This returns a new jQuery object so you can use it like jQuery element.

    The jQuery.text() method: $('div').text('some text') This method is recommended if you putting just text inside the element. It will escape all special characters like '<'. Instead it puts <. This avoiding XSS attacks unlike jQuery.html() method. You can look Security Considerations at jQuery docs about .html method.

    // Create a div element with jQuery which will hold all items.
    var $tree = $('
    ', {id: 'items-tree'}); //Loop all items and create elements for each for (var key in grocery_list) { var $gItem = $('
    ', { id: 'grocery_item', class: 'container' }); var $item = $('
    ', { class: 'item' }).text(key); $gItem.append($item); var $category = $('
    ', { class: 'category' }).text(grocery_list[key].category); $gItem.append($category); var $price = $('
    ', { class: 'price' }).text(grocery_list[key].price); $gItem.append($price); $tree.append($gItem); }

    JSFiddle

提交回复
热议问题