简体   繁体   English

循环通过 Javascript Object 并添加到 HTML Div

[英]Looping through Javascript Object and adding to HTML Div

I am working on a game and have run into a problem that I have been stuck on for hours.我正在开发一款游戏,但遇到了一个我已经坚持了好几个小时的问题。 I have an object, and I want to write a loop which will take all the values in this object, and stick them into an html div.我有一个 object,我想编写一个循环,它将获取此 object 中的所有值,并将它们粘贴到 html div 中。 The way I am doing this is, I have taken a div, I am cloning it and giving all the child elements new values.我这样做的方式是,我采用了一个 div,我正在克隆它并为所有子元素赋予新值。 Then I want to use the DOM manipulation to insert the values from one key, into a div with a heading and two paragraphs.然后我想使用 DOM 操作将一个键中的值插入到一个带有标题和两个段落的 div 中。 Here is the code.这是代码。

Index.html索引.html

<div id = "all_asset" style = "display: none;">
    <div class = "touch_box col-sm-12" style = "height: 150px; display: none;" id = "asset_touchbox">
        <br><h id = "asset_name"></h>
        <p1 id = "asset_price"></p1><hr>
        <p id = "asset_age"></p><hr>
    </div>    
</div>

play.js play.js

function assetsList(){
    Object.keys(assets).forEach(key => {
        for (var i = 1; i < Object.keys(assets).length; i++){
    
            //duplicate box
            var list_box = document.getElementById("asset_touchbox");
            var clone_box = list_box.cloneNode(true);
            clone_box.id = "list_assets" + String(i);
            document.getElementById("all_asset").appendChild(clone_box);

            //get id of child elements
            clone_box.getElementsByTagName('h')[0].id = "asset_name" + String(i);
            clone_box.getElementsByTagName('p1')[0].id = "asset_price" + String(i);
            clone_box.getElementsByTagName('p')[0].id = "asset_age" + String(i);
            list_box.parentNode.appendChild(clone_box);
            //show box
            clone_box.style.display = "block";

            var asset_name = assets[key][0];
            var asset_age = assets[key][1];
            var asset_price = assets[key][2];

            document.getElementById("asset_name" + String(i)).innerHTML = asset_name;
            document.getElementById("asset_price" + String(i)).innerHTML = asset_age;
            document.getElementById("asset_age" + String(i)).innerHTML = asset_price;
        }
      });      
}

Javascript Object Javascript Object

//asset name, asset age, asset cost
assets = {1: ["Boat", 0, "10000"], 2: ["Carriage", 0, "10000"]}

So what I pretty much want to do is - Create two divs, each one has the information from each key.所以我非常想做的是 - 创建两个 div,每个 div 都有来自每个键的信息。 I hope I made sense.我希望我是有道理的。 Please let me know if I didn't.如果我没有,请告诉我。 Thanks!谢谢!

You can use class to simplify the code.您可以使用class来简化代码。

Here is an example:这是一个例子:

 // The original object given by you const givenAssets = { 1: ['Boat', 0, '10000'], 2: ['Carriage', 2, '30000'] }; // Get #all_asset const assetContainer = document.querySelector('#all_asset'); // Define a class class Asset { // Set parameters constructor(id, name, price, age) { this.id = id; this.name = name; this.price = price; this.age = age; } // Create HTML addHtml() { // HTML elements as string let html = ` <div class="touch_box col-sm-12" id="list_asset${this.id}"> <br> <h4 id="asset_name${this.id}">${this.name}</h4> <p id="asset_price${this.id}">${this.price}</p> <hr> <p id="asset_age${this.id}">${this.age}</p> <hr> </div>`; // Add HTML element before the end of #all_asset assetContainer.insertAdjacentHTML('beforeend', html); } } // Make instances and put them into an array let assets = []; for (const key in givenAssets) { assets.push(new Asset(key, givenAssets[key][0], givenAssets[key][1], givenAssets[key][2])) } // Execute.addHtml() on each asset one by one. assets.forEach(asset => asset.addHtml());
 <div id="all_asset"></div>

Personally, I'd build the asset html inside your forEach function instead of cloning placeholder html.就个人而言,我会在你的 forEach function 中构建资产 html 而不是克隆占位符 html。 The code below should create the structure you're looking for.下面的代码应该创建您正在寻找的结构。 Good luck!祝你好运!

index.html索引.html

<div id="all_asset"/>

play.js play.js

const assets = {
  1: ["Boat", 0, "10000"],
  2: ["Carriage", 0, "10000"]
}

function assetsList() {
  Object.keys(assets).forEach(key => {
    // get current asset data
    const assetData = assets[key];
    // create asset container
    const container = document.createElement("div");
    // create and append asset header
    const header = document.createElement('h1');
    header.appendChild(document.createTextNode(assetData[0]))
    // create and append first p
    const p1 = document.createElement('p')
    p1.appendChild(document.createTextNode(assetData[1]))
    // crreate and append second p
    const p2 = document.createElement('p')
    p2.appendChild(document.createTextNode(assetData[2]))
    // fill out the asset container
    container.appendChild(header)
    container.appendChild(p1)
    container.appendChild(p2)
    // append the whole thing to the parent
    document.getElementById("all_asset").appendChild(container);
  })
};

You may want to consider refactoring your representation of the assets as an array of objects.您可能需要考虑将资产表示重构为对象数组。 For example,例如,

let assets = [
  {
    name: 'boat',
    age: 0,
    price: 10000,
  },
  {
    name: 'carriage',
    age: 0,
    price: 10000,
  },
];

Following your initial idea of using the forEach method to iterate over the assets, you could dynamically insert a div for every asset.按照您最初使用forEach方法迭代资产的想法,您可以为每个资产动态插入一个 div。

assets.forEach(({ name, age, price }) => {
  let touchBox = document.createElement('div');
  touchBox.classList.add('touch_box', 'col-sm-12');
  touchBox.id = 'asset_touchbox';
  touchBox.style.height = '150px';

  let nameElt = document.createElement('h5');
  nameElt.id = 'asset_name';
  nameElt.innerHTML = name;

  let priceElt = document.createElement('p');
  priceElt.id = 'asset_price';
  priceElt.innerHTML = price;

  let ageElt = document.createElement('p');
  ageElt.id = 'asset_age';
  ageElt.innerHTML = age;

  touchBox.appendChild(nameElt);
  touchBox.appendChild(priceElt);
  touchBox.appendChild(ageElt);

  document.querySelector('#list_box').appendChild(touchBox);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM