创建多个 DIV 并分配唯一 ID

Create multiple DIVs and assign unique ID

我正在尝试创建多个 div 并使用 javascript 为它们分配一个唯一 ID,最好是控制台日志中打印的状态名称。我尝试的任何东西都不起作用。有什么建议吗?我已经关注了我可以在这个论坛上找到的每一个类似的问题和答案,但对我的情况没有任何帮助。

<html>
    <head>
        <meta charset="UTF-8">
        <title>Untitled Document</title>
    </head>
    
    <body>
        
        <div id="myDiv">
        </div>
        
        <script>
    
            getData(); //call function
            
            async function getData(){ //define an asynchronous function

                var response = await fetch('covid.csv'); //call data and assign it to a variable
                var data = await response.text(); //parse the text from the response and assign it to variable    
                console.log(data);
                
                var table = data.split('\n').slice(1, -1); //delineate rows of the table by splitting them at the line break. This results in an array such as: [0] Alaska, 12, 1.33 etc
                console.log(table);

                table.forEach(row => {
                    var columns = row.split(','); 
                    var state = columns[0];
                    var deaths = columns[1];
                    var deathsPer = columns[2];
                    console.log(state, deaths, deathsPer);
                             
                  /*
                  document.getElementById("myDiv").innerHTML = //DOESN'T WORK need to create new div for each row
                    state + 
                    " death toll is " + 
                    deaths + 
                    " and a death rate of " + 
                    deathsPer
                    ;
                   */

                    for(var i=0;i<50;i++){   //DOESN'T WORK creates 50 divs x50
                    var newDiv = document.createElement("div");
                    document.body.appendChild(newDiv);
                    newDiv.setAttribute("id", 'textBar' + i);
                    }
                                                                 
                });
            }
                        
        </script>
        
    </body>
</html>

您已经在使用 forEach 进行循环,因此不需要额外的循环。在那个额外的循环中,您没有设置 innerHML:

ES6版本

const $myDiv = document.getElementById('myDiv');

(async function getData() {
  // Just for the demo
  const data = '\nVirginia,12,1\nCalifornia,24,3\nFlorida,36,11\n';
  const table = data.split('\n').slice(1, -1);
  
  table.forEach(row => {
    const [ state, deaths, deathsPer ] = row.split(','),
      $newDiv = document.createElement("div");
      
    $newDiv.innerHTML = `${state} death toll is ${deaths}
                         and a death rate of ${deathsPer}`;
    $newDiv.id = `textBar_${state}`;
    $myDiv.appendChild($newDiv);
  });
})();
<div id="myDiv"></div>

更容易理解的版本(仅包含您已经使用的 ES6 功能)

const $myDiv = document.getElementById('myDiv');

getData();

async function getData() {
  // Just for the demo
  const data  = '\nVirginia,12,1\nCalifornia,24,3\nFlorida,36,11\n',
        table = data.split('\n').slice(1, -1);
  
  table.forEach(row => {
    const columns   = row.split(','),
          state     = columns[0],
          deaths    = columns[1],
          deathsPer = columns[2],
          $newDiv   = document.createElement("div");
      
    $newDiv.innerHTML = state + " death toll is " + deaths
                      + " and a death rate of " + deathsPer;
                      
    $newDiv.id = "textBar_" + state;
    $myDiv.appendChild($newDiv);
  });
}
<div id="myDiv"></div>

可能是因为您正在创建的 div 的 if 不是唯一的,因为您是第一次创建 textBar1..textBar50 和 forEach 的第二个圆圈,您正在创建相同的 id div.

尝试像这样向 forach 添加索引:table.forEach((row, id) => { 并在设置属性的行上创建如下内容:

newDiv.setAttribute("id", textBar-${id} - ${i} );