如何在预先给定的div中动态创建div

时间:2018-08-29 17:48:11

标签: javascript jquery html

我拥有的标记:

   <div id="list"></div>

有一个大物体。我想做的是根据对象字段创建div,但不对其进行硬编码。所以我这样做:

for (var key in table) {
    console.log(key);
    if (table.hasOwnProperty(key)) {
        var div_card[key] = document.createElement('div');
        div_card[key].addClass('card');
        $('.card').innerHTML = table[key].name;
        div_card[key].appendTo('#list');
    }
}

有一个预先给定的ID列表div,我想在其中添加一个新的类卡div,并且有这些类的multiole div。添加课程时,我得到

Uncaught TypeError: Cannot read property 'addClass' of undefined
    at js.js:2604
(anonymous) @ js.js:2604

我添加了key作为索引,因为这将是div(数组)的集合。代码有什么问题?

P.S。 最后我想获得这种结构

#list
  .card*100

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,则想从<div>列表中的对象创建table。我会使用jQuery进行以下操作。

var table = [{
    "atomicNumber": 1,
    "symbol": "H",
    "name": "Hydrogen",
    "atomicMass": "1.00794(4)",
    "cpkHexColor": "FFFFFF",
    "electronicConfiguration": "1s1",
    "electronegativity": 2.2,
    "atomicRadius": 37,
    "ionRadius": "",
    "vanDelWaalsRadius": 120,
    "ionizationEnergy": 1312,
    "electronAffinity": -73,
    "oxidationStates": "-1, 1",
    "standardState": "gas",
    "bondingType": "diatomic",
    "meltingPoint": 14,
    "boilingPoint": 20,
    "density": 0.0000899,
    "groupBlock": "nonmetal",
    "yearDiscovered": 1766
  },
  {
    "atomicNumber": 2,
    "symbol": "He",
    "name": "Helium",
    "atomicMass": "4.002602(2)",
    "cpkHexColor": "D9FFFF",
    "electronicConfiguration": "1s2",
    "electronegativity": "",
    "atomicRadius": 32,
    "ionRadius": "",
    "vanDelWaalsRadius": 140,
    "ionizationEnergy": 2372,
    "electronAffinity": 0,
    "oxidationStates": "",
    "standardState": "gas",
    "bondingType": "atomic",
    "meltingPoint": "",
    "boilingPoint": 4,
    "density": 0.0001785,
    "groupBlock": "noble gas",
    "yearDiscovered": 1868
  }
]

var $list = $('#list');

table.forEach(function(obj) {
  $('<div>', {
    class: 'card',
    text: obj.name
  }).appendTo($list);
})
.card {
  border: 1px solid #999;
  height: 20px;
  padding: 2px;
  margin-bottom: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="list"></div>