使用循环创建新的div,在每个新div上附加子节点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用循环创建新的div,在每个新div上附加子节点相关的知识,希望对你有一定的参考价值。

我正在为我的一个课程完成作业,我需要以下方面的帮助:

使用javascript,我必须为JSON对象中的每本书(总共50本,下面一个示例)创建div,并将每本书的图像,标题和描述放在新创建的div中。

以下是该对象中的一本书的示例:

var itunesResponse = {
  "results": [
    {
      "fileSizeBytes": 468847,
      "artistViewUrl": "https:\/\/itunes.apple.com\/us\/artist\/brad-land\/5526375?mt=11&uo=4",
      "trackCensoredName": "Goat",
      "trackViewUrl": "https:\/\/itunes.apple.com\/us\/book\/goat\/id420798692?mt=11&uo=4",
      "artworkUrl60": "http:\/\/is4.mzstatic.com\/image\/thumb\/Publication18\/v4\/1c\/48\/62\/1c4862bd-1a5d-0a7c-7143-2878aed682f8\/source\/60x60bb.jpg",
      "artworkUrl100": "http:\/\/is4.mzstatic.com\/image\/thumb\/Publication18\/v4\/1c\/48\/62\/1c4862bd-1a5d-0a7c-7143-2878aed682f8\/source\/100x100bb.jpg",
      "currency": "USD",
      "artistId": 5526375,
      "artistName": "Brad Land",
      "genres": [
        "Biographies & Memoirs",
        "Books",
        "Professional & Technical",
        "Education",
        "Nonfiction",
        "Social Science"
      ],
      "kind": "ebook",
      "price": 9.99,
      "description": "<b>Soon to be a major motion picture starring Nick Jonas, this&#xa0;searing memoir of fraternity culture and the perils of hazing&#xa0;provides an unprecedented window&#xa0;into the emotional landscape of young men.<\/b><br \/><br \/>Reeling from a terrifying assault that has left him physically injured and psychologically shattered, nineteen-year-old Brad Land must also contend with unsympathetic local police, parents who can barely discuss \u201cthe incident\u201d (as they call it), a brother riddled with guilt but unable to slow down enough for Brad to keep up, and the feeling that he\u2019ll never be normal again.<br \/><br \/>When Brad\u2019s brother enrolls at Clemson University and pledges a fraternity, Brad believes he\u2019s being left behind once and for all. Desperate to belong, he follows. What happens there\u2014in the name of \u201cbrotherhood,\u201d and with the supposed goal of forging a scholar and a gentleman from the raw materials of boyhood\u2014involves torturous late-night hazing, heartbreaking estrangement from his brother, and, finally, the death of a fellow pledge. Ultimately, Brad must weigh total alienation from his newfound community against accepting a form of brutality he already knows too well.<br \/><br \/><i>From the Hardcover edition.<\/i>",
      "formattedPrice": "$9.99",
      "artistIds": [
        5526375
      ],
      "genreIds": [
        "9008",
        "38",
        "9029",
        "10037",
        "9002",
        "10120"
      ],
      "releaseDate": "2004-02-03T08:00:00Z",
      "trackId": 420798692,
      "trackName": "Goat",
      "userRatingCount": 16,
      "averageUserRating": 3.5
    }
  ]
}

我计划使用循环创建所有内容,但每次我尝试通过循环将标题(标题)附加到新div中时,所有内容都会在最后创建的div中结束。

我最近尝试过的代码:

let body = document.getElementById('wrapper');
let newImg = document.createElement('img');
let newTit = document.createElement('h3');
let newDes = document.createElement('p');
        for(i=0; i<itunesResponse.results.length; i++ ){
            let newDiv = document.createElement('div');
            body.appendChild(newDiv);
            newDiv.appendChild(newTit);
            newDiv.style.color = 'rgb(100,100,100)';
            let titVal = document.createTextNode(itunesResponse.results[i].trackName);
            newTit.appendChild(titVal);
        }
答案

您需要将新div附加到DOM并将新标题的创建移动到循环内部。

let body = document.getElementById('wrapper');

for (let i = 0; i < itunesResponse.results.length; i++) {
    let newDiv = document.createElement('div');
    newDiv.style.color = 'rgb(100,100,100)';
    body.appendChild(newDiv);

    let newTit = document.createElement('h3');
    newDiv.appendChild(newTit);

    let titVal = document.createTextNode(itunesResponse.results[i].trackName);
    newTit.appendChild(titVal);
}
另一答案

您在itunesResponse的定义中存在语法错误,在下面进行了更正。 此外,您还需要为循环内的每个条目创建新元素。

var itunesResponse = {
  "results": [{
      "trackName": "Goat"
    },
    {
      "trackName": "Another Track"
    }
  ]
};

let body = document.getElementById('wrapper');

for (i = 0; i < itunesResponse.results.length; i++) {
  let newDiv = document.createElement('div');
  let newTit = document.createElement('h3');
  body.appendChild(newDiv);
  newDiv.appendChild(newTit);
  newDiv.style.color = 'rgb(100,100,100)';
  let titVal = document.createTextNode(itunesResponse.results[i].trackName);
  newTit.appendChild(titVal);
}
<div id="wrapper"></div>
另一答案

在循环内部进行变量声明可以让身体离开循环,尽管这不是做出需要的最佳方法

以上是关于使用循环创建新的div,在每个新div上附加子节点的主要内容,如果未能解决你的问题,请参考以下文章

子节点的应用

使用已获取的 MySQL 数据行将新的 MySQL 数据附加到 DIV

怎样给jQuery动态附加新的元素

用javascript添加新的div元素[重复]

获取新的 MySQL 条目并动态追加到现有的 div

插入节点appendChild()