在HTML中显示JavaScript对象 [英] Display JavaScript Object in HTML

查看:91
本文介绍了在HTML中显示JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的对象:

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 }
}

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

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

<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>

我知道如何在JS中循环一个Object,但我不知道如何显示这些DOM中的项目。我相信我可以使用jQuery追加功能,但我不确定如何。

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.

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

Any help would be appreciated. thanks!

推荐答案

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

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:

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 here:

http://jsfiddle.net/5jhgbg9w/

编辑:请把这个作为一个例子(这是正确的,因为你正在学习)。正如其他人指出的那样 - 这不是最好的方法。尝试结合其他示例,特别是那些不将HTML组成字符串的示例。对于像这样的简单任务,它很简单,但是代码越多,代码就会变得更加混乱。我相信你的学习进化会让你在那里:-)为每个人欢呼

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中显示JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆