【问题标题】:Creating new divs using loop, appending child nodes on each new div使用循环创建新 div,在每个新 div 上附加子节点
【发布时间】:2018-08-14 15:56:50
【问题描述】:

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

使用 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分配一个ID来区分它们吗?
  • 或在将 div 放入 DOM 之前创建 div 并填充其内容?
  • 请出示您尝试的代码,让我们知道具体出了什么问题。
  • 您不断重复使用相同的 newTit 变量。您是否每次都尝试在循环中创建一个新的?
  • 将它的创建移到循环内部

标签: javascript html loops dom


【解决方案1】:

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);
}
&lt;div id="wrapper"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    您需要将新 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);
    }
    

    【讨论】:

      【解决方案3】:

      在循环内进行变量声明,您可以将主体排除在循环之外,尽管这不是满足需要的最佳方式

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-20
        • 2016-07-16
        • 1970-01-01
        • 2021-12-16
        • 2019-05-15
        • 1970-01-01
        相关资源
        最近更新 更多