Display JavaScript Object in HTML

后端 未结 4 1014
予麋鹿
予麋鹿 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 09:00

    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 = $('
    '); wrapper.append(container); container.append('
    ' + key +'
    '); container.append('
    ' + grocery_list[key].category +'
    '); container.append('
    ' + grocery_list[key].price +'
    '); }

    jsfiddle here:

    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

提交回复
热议问题