遍历数组并追加到不同的HTML元素

时间:2019-03-01 17:08:42

标签: javascript

我有3个HTML列和一个包含3个对象的数组。我试图遍历数组并将数组内的值附加到每个HTML列。因此,数组中的第一个对象到第一列,第二个对象到第二列。哪种类型的循环最适合这种情况?

var shortenedCast = fullCast.slice(0, 3);
var arrayLength = shortenedCast.length; //3
var columns = document.getElementsByClassName("panel-item");
var characterP = document.getElementsByClassName("character");

for (var i = 0; i < arrayLength; i++) {
  console.log(shortenedCast[i].character);
  //John wick
  //Viggo Tarasov
  //Iosef Tarasov
  characterP.textContent = shortenedCast[i].character;
}

console.log(shortenedCast);
<div class="column small-4">
  <div class="panel-item">
    <p class="character"></p>
  </div>
</div>

<div class="column small-4">
  <div class="panel-item">
    <p class="character"></p>
  </div>
</div>

<div class="column small-4">
  <div class="panel-item">
    <p class="character"></p>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

我正在考虑一种更动态的方法,而不必在每次增加数组时都添加新的Div。

arr = ['John wick', 'Viggo Tarasov', 'Iosef Tarasov'];

function createColumns(arr) {
  let colItems = [];

  arr.map(item => {
    colItems.push(`
      <div class="column small-4">
        <div class="panel-item">
          <p class="character">${item}</p>
        </div>
      </div>
      `);
  });

  return colItems;
}

document.getElementById('someDivID').innerHTML = createColumns(arr).join('');

答案 1 :(得分:0)

感谢异端猴子的成功

对于观看此解决方案的人来说,是在角色P前面添加[i]

<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />