1

我希望将存储在数组中的值添加到带有 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();
4

3 回答 3

2

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

请注意,document.querySelectorAll默认情况下返回的元素数组是可迭代的。你不需要使用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>

于 2020-03-30T08:51:43.250 回答
1

将第二个参数设为forEach您要迭代的索引,以识别nums要设置的元素:

document.querySelectorAll('.score').forEach((el, i) => {
  el.textContent = nums[i];
});
于 2020-03-30T08:46:24.313 回答
0

使用经典的 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>

于 2020-03-30T08:51:39.417 回答