通过DOM显示数组中的对象

时间:2016-08-25 22:37:56

标签: javascript html arrays object dom

  var products = [{
    "name": "Lusicious Jello Mix",
    "description": ["Very Elegant", "Trending item", "Come in Purple"],
    "price": 80.65
  }, {
    "name": "Tarnished Standing Desk",
    "description": ["Modular", "Works for both Tall and Loud People", "Smells like Productivity"],
    "price": 1654.99
  }, {
    "name": "Hand-made Hand Grenades",
    "description": ["Such gift!", "Much boom!", "Very safe for kids"],
    "price": 10.44
  }, {
    "name": "Pan-fried Cookie Dough",
    "description": ["Chocolate", "Family-size", "Hot Mess"],
    "price": 16.99
  }, {
    "name": "Fancy Dress Hanger",
    "description": ["Keep organized", "On Sale"],
    "price": 67.32
  }, {
    "name": "Snarky Britsh Mustache 3-Pack",
    "description": ["Sharing is caring!", "Hugs not drugs", "As seen on 'So You Think You Can Dance - Nigeria!'"],
    "price": 1.99
  }, ];

for (var x=0; x<products.length; x++){
        //PRODUCT NAME
        var prodname = document.createElement("h3");
        prodname.innerHTML = products[x].name;
        var listname = document.getElementById("name");
        listname.appendChild(prodname);

        var proddesc = document.createElement("h3");
        proddesc.innerHTML = products[x].description;
        var listdesc = document.getElementById("description");
        listdesc.appendChild(proddesc);

        var prodprice = document.createElement("h3");
        prodprice.innerHTML = products[x].price;
        var listprice = document.getElementById("price");
        listprice.appendChild(prodprice);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Shopping Cart</title>
    <script src="js/app.js"></script>
    <link rel="stylesheet" href="css/styles.css"></link>
</head>
<body>
    <div>
        <div id="shopHead"><h3>Shopping Cart<h3/>
        <h3 id="name"></h3>
        <h3 id="description"></h3>
        <h3 id="price"></h3>

</div>

    </div>
</body>
</html>

这是我在名为products的数组中的对象。我使用数组然后使用DOM在我的HTML页面中显示。然而它并没有按顺序出现。我想在位置0的数组中显示名称,然后在位置0处显示描述,最后定价在位置0.相反,它显示我的所有名称,然后是所有描述,后跟所有价格。这是一个简单的解决方案,我确定但是我被卡住了。

1 个答案:

答案 0 :(得分:0)

试试这个

var displayBox = document.createElement("h3");
displayBox.innerHTML = products[x].name + " "+ products[x].description + " "+products[x].price;
var listname = document.getElementById("name");
listname.appendChild(displayBox);