在 HTML 中显示 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27266901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:57:09  来源:igfitidea点击:

Display JavaScript Object in HTML

javascriptobjectdom

提问by theartofbeing

I have a object that looks like this:

我有一个看起来像这样的对象:

var grocery_list = {
  "Banana": { category: "produce", price: 5.99 },
  "Chocolate": { category: "candy", price: 2.75 },
  "Wheat Bread": { category: "grains and breads", price: 2.99 }
}

And I want to be able to display each item in the object in HTML like this:

我希望能够像这样以 HTML 显示对象中的每个项目:

<div id="grocery_item" class="container">
    <div class="item">Item Here</div>
    <div class="category">Category Here</div>
    <div class="price">Price Here</div>
</div>

I know how to loop through an Object in JS, but I'm not sure how to display those items in the DOM. I believe I could use the jQuery append function but I'm not sure how.

我知道如何在 JS 中循环遍历一个对象,但我不确定如何在 DOM 中显示这些项目。我相信我可以使用 jQuery append 函数,但我不确定如何使用。

Any help would be appreciated. thanks!

任何帮助,将不胜感激。谢谢!

回答by Ivan Sivak

This is how you can do it using jQuery (as you mention you'd like to use jQuery first). But it's not the best way how to it. If you're open to learn better methods then check some of the MV* frameworks (AngularJS, Ember etc.). Anyway, here is just an example:

这是使用 jQuery 的方法(正如您提到的,您想先使用 jQuery)。但这不是最好的方法。如果您愿意学习更好的方法,请查看一些 MV* 框架(AngularJS、Ember 等)。无论如何,这里只是一个例子:

var grocery_list = {
  "Banana": { category: "produce", price: 5.99 },
  "Chocolate": { category: "candy", price: 2.75 },
  "Wheat Bread": { category: "grains and breads", price: 2.99 }
}

var wrapper = $('#wrapper'), container;
for (var key in grocery_list){
    container = $('<div id="grocery_item" class="container"></div>');
    wrapper.append(container);
    container.append('<div class="item">' + key +'</div>');
    container.append('<div class="category">' + grocery_list[key].category +'</div>');
    container.append('<div class="price">' + grocery_list[key].price +'</div>');
}

jsfiddle here:

jsfiddle在这里:

http://jsfiddle.net/5jhgbg9w/

http://jsfiddle.net/5jhgbg9w/

EDIT: Please, take this really as an example (which is OK since you're learning). As others pointed out - it's not the best method. Try to combine other examples, particularly the ones which do not compose HTML as string. For easy tasks like this it's straightforward but more code you would add more messy the code becomes. I believe your "learning evolution" would get you there anyway :-) Cheers everyone

编辑:请以这个为例(因为你正在学习,所以没关系)。正如其他人指出的那样 - 这不是最好的方法。尝试结合其他示例,尤其是那些不将 HTML 组成为字符串的示例。对于像这样的简单任务,它很简单,但是您添加的代码越多,代码就会变得越混乱。我相信你的“学习进化”无论如何都会让你到达那里:-) 为大家干杯

回答by Ifch0o1

You can create HTML elements with jQuery: $('<div>', {attr1: value, attr2: value});This returns a new jQuery object so you can use it like jQuery element.

您可以使用 jQuery 创建 HTML 元素:$('<div>', {attr1: value, attr2: value});这将返回一个新的 jQuery 对象,因此您可以像使用 jQuery 元素一样使用它。

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 &lt. This avoiding XSS attacks unlike jQuery.html() method. You can look Security Considerations at jQuery docsabout .html method.

jQuery.text() 方法:$('div').text('some text')如果您只将文本放入元素中,则推荐使用此方法。它将转义所有特殊字符,如'<'. 相反,它把&lt. 与 jQuery.html() 方法不同,这避免了 XSS 攻击。您可以在有关 .html 方法的jQuery 文档中查看安全注意事项。

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

  var $item = $('<div>', {
    class: 'item'
  }).text(key);
  $gItem.append($item);

  var $category = $('<div>', {
    class: 'category'
  }).text(grocery_list[key].category);
  $gItem.append($category);

  var $price = $('<div>', {
    class: 'price'
  }).text(grocery_list[key].price);
  $gItem.append($price);

  $tree.append($gItem);
}

JSFiddle

JSFiddle

回答by Raghava Rudrakanth P V

The parent div <div id="grocery_item" class="container">will be repeated for the no. of items in the grocery list. The "id" of this parent div will be generated randomly for example item @index 0 will be "grocery_item0"

父 div<div id="grocery_item" class="container">将重复编号。购物清单中的物品。此父 div 的“id”将随机生成,例如 item @index 0 将是“grocery_item0”

For each loop item create the parent div's first, then start appending the details to the parent div's using (another loop). Below will be sample jquery,

对于每个循环项,首先创建父 div,然后开始使用(另一个循环)将详细信息附加到父 div。下面将是示例 jquery,

$( ".grocery_item0" ).append( "" );

$(".grocery_item0").append("");

回答by Alexandru Aliu

I will pass by the fact that your list definition is not exactly the best and I say this:

我将忽略您的列表定义并不完全是最好的事实,我这样说:

Using jQuery you could do that:

使用 jQuery 你可以做到:

<script>
var _parent = $(".container").parent();
_parent.empty();

var _html;
$.each(grocery_list,function(prop, val){
    _html = "<div id=\"grocery_item\" class=\"container\">";
    _html += "<div class=\"item\">"+prop+"</div>";
    _html += "<div class=\"category\">"+val.category+"</div>";
    _html += "<div class=\"price\">"+val.price+"</div>";
    _html += "</div>";

    _parent.append(_html);
});
</script>

Note*: It's not recomanded to maanipulate the DOM by creating HTML strings. This is just an fast sample for your school assignment.

注意*:不建议通过创建 HTML 字符串来操作 DOM。这只是您学校作业的快速示例。