迭代一个JSON对象并将appendChild附加到DIV

时间:2018-12-08 22:02:09

标签: javascript html json dom

我有一个JSON对象,例如:

{ Naam: "bert", Achternaam: "Kopers"}

我想将此呈现为HTML页面上的DIV元素。它应该看起来像这样:

   <div id = "contents>
        <div class="setting-label">
            Naam
        </div>
        <div class="setting-value">
            bert    
        </div>
    </div>
    <div class="setting-row">
            <div class="setting-label">
                AchterNaam
            </div>
            <div class="setting-value">
                kopers  
            </div>
        </div>

最好是不使用innerHTML来实现。因此,使用appendChild。代码看起来如何?

1 个答案:

答案 0 :(得分:0)

这应该有效:

onload = function() {
      var person = {Naam: "Bert", Achternaam: "Kopers"};
      var contents = document.getElementById("contents");

      for(var key in person) {
        var personDiv = document.createElement("div");
      
        var div1 = document.createElement("div");
        var text1 = document.createTextNode(key);
        div1.appendChild(text1);
        
        var div2 = document.createElement("div");
        var text2 = document.createTextNode(person[key]);
        div2.appendChild(text2);
        
        personDiv.appendChild(div1);
        personDiv.appendChild(div2);
        
        contents.appendChild(personDiv);
      }
}
<div id="contents"></div>

将为您提供HTML输出:

<div id="contents">
  <div>
    <div>Naam</div>
    <div>Bert</div>
  </div>
  <div>
    <div>Achternaam</div>
    <div>Kopers</div>
  </div>
</div>