在JS中创建HTML元素(没有jQuery)?我究竟做错了什么?

时间:2017-10-30 01:56:32

标签: javascript html arrays node.js

我是node.js的新手。这是我的代码:
My Code

更具体地说,这是我对JS的所作所为:

let torontoTeams = [
    {"name": "Raptors", "description": "The Raptors compete in the National Basketball Association (NBA), as a member club of the league's Eastern Conference Atlantic Division."},

    {"name": "Maple Leafs", "description": "The Maple Leafs are one of the 'Original Six' NHL teams, and have won the Stanley Cup 13 times."},

    {"name": "Blue Jays", "description": "The Blue Jays compete in Major League Baseball (MLB) as a member club of the American League (AL) East division."}
];
for (let i=0; i < torontoTeams.length; i++) {

    let newSection = document.createElement('section');
    document.appendChild(newSection);

    let newTeam = document.createElement('h1');
    newTeam.appendChild(document.createTextNode(torontoTeams[i].name));

    let newDesc = document.createElement('P');
    newDesc.appendChild(document.createTextNode(torontoTeams[i].description));

    document.createElement(newSection);
    newSection.appendChild(newTeam);
    newSection.appendChild(newDesc);
};

我不确定在创建HTML元素时我出了什么问题。

1 个答案:

答案 0 :(得分:1)

您只能将一个元素附加到document。将section附加到document.body或创建容器,并使用document.querySelector

进行定位

&#13;
&#13;
var body = document.body,
    torontoTeams = [
    {"name": "Raptors", "description": "The Raptors compete in the National Basketball Association (NBA), as a member club of the league's Eastern Conference Atlantic Division."},

    {"name": "Maple Leafs", "description": "The Maple Leafs are one of the 'Original Six' NHL teams, and have won the Stanley Cup 13 times."},

    {"name": "Blue Jays", "description": "The Blue Jays compete in Major League Baseball (MLB) as a member club of the American League (AL) East division."}
];


for (let i=0; i < torontoTeams.length; i++) {

    var newSection = document.createElement('section');
    body.appendChild(newSection); // append to body.

    var newTeam = document.createElement('h1');
    newTeam.appendChild(document.createTextNode(torontoTeams[i].name));

    var newDesc = document.createElement('P');
    newDesc.appendChild(document.createTextNode(torontoTeams[i].description));

    // document.createElement(newSection); What is this suppose to do? It doesn't work.
    
    newSection.appendChild(newTeam);
    newSection.appendChild(newDesc);
    
};
&#13;
section {
  display: block;
  width: 100vh;
  height: 33vh;
  background-color: blue;
}
&#13;
&#13;
&#13;