如何将存储在数组中的值作为 textContent 或 innerText 添加到具有相同 class 名称的 div 元素

How to add values, that are stored in an array, as textContent or innerText to div elements with the same class name

我想将存储在数组中的值添加到具有 className .score 的 div 元素中。有 12 个元素和 12 个值。例如第一个元素:<div class="score">15<div> 等等。 我尝试的代码将数组的最后一个值添加到所有元素,这当然不是我想要的。谢谢。

var nums = [15, 15, 14, 14, 13, 12, 12, 11, 11, 11, 28, 28];

function addValue() {
   var e = document.querySelectorAll('.score')
   Array.from(e).forEach(el => {
      for (let value of nums) {
         el.textContent = value
      }
   })
}

addValue();

将第二个参数传递给 forEach,您正在迭代的索引,以确定要设置 nums 中的哪个元素:

document.querySelectorAll('.score').forEach((el, i) => {
  el.textContent = nums[i];
});

使用经典的for循环,

var nums = [15, 15, 14, 14, 13, 12, 12, 11, 11, 11, 28, 28];
var arr = document.querySelectorAll('.score');
for (i = 0; i < arr.length; ++i) {
  arr[i].textContent = nums[i];
}
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>

您可以使用 forEach 循环的第二个参数(数组的索引)来获取 nums 数组的值,因为两个数组的长度相同。

Note that the element array return by document.querySelectorAll is by default iterable. You don't need to use Array.from.

示例:

(function() {
    var nums = [15, 15, 14, 14, 13, 12, 12, 11, 11, 11, 28, 28];

    function addValue() {
        var e = document.querySelectorAll('.score')
        e.forEach((el, index) => {
            el.textContent = nums[index]
        });
    }
    addValue();
})()
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>

或者您可以使用 Array.from 回调方法来填充 div。

示例:

(function() {
    var nums = [15, 15, 14, 14, 13, 12, 12, 11, 11, 11, 28, 28];

    function addValue() {
        Array.from(
            document.querySelectorAll('.score'),
            (el, index) => el.textContent = nums[index]
        );
    }
    addValue();
})()
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>
<div class="score"></div>