如何通过Javascript将顺序类名附加到<li>

时间:2016-01-09 18:21:37

标签: javascript jquery css

在for循环中创建顺序类名的最简单方法是什么?

3 个答案:

答案 0 :(得分:0)

使用&#34; fret-row&#34; +(i + 1)&#34;字符串&#34; +(j + 1)

for(var i = 0; i < frets; i++){
  var fretRow = document.createElement("ul");
  fretRow.classList.add("fret-row" + (i+1));
  for(var j = 0; j < strings; j++){
    var fret = document.createElement("li");
    fret.classList.add("string" + (j+1));
    fretRow.appendChild(fret);
  }
  fretboard.appendChild(fretRow);
}

答案 1 :(得分:0)

您可以从正在添加的类中的for循环中连接迭代加1,例如:

for(var i = 0; i < frets; i++){
  var fretRow = document.createElement("ul");
  fretRow.classList.add("fret-row-" + (i + 1));
  
  // 6 times, create a li item, add class "string, and append to the fretRow ^ 
  for(var j = 0; j < strings; j++){
    var fret = document.createElement("li");
    fret.classList.add("string-" + (j + 1));

    fretRow.appendChild(fret);
  }
 
  //append entire fretRow (now 'frets' and 'strings' to the fretboard div)
  fretboard.appendChild(fretRow);
}

答案 2 :(得分:0)

您可以像下面一样更改for循环。将fretRow.classList.add("fret-row")更改为fretRow.classList.add("fret-row", "fret-row"+(i+1));,将fret.classList.add("string")更改为fret.classList.add("string"+(j+1))

for(var i = 0; i < frets; i++){
   var fretRow = document.createElement("ul");
   fretRow.classList.add("fret-row", "fret-row"+(i+1));

   for(var j = 0; j < strings; j++){
        var fret = document.createElement("li");
        fret.classList.add("string"+(j+1));
        fretRow.appendChild(fret);
   }

   fretboard.appendChild(fretRow);
}

CODE PEN DEMO