content = document.getElementsByClassName('outercontent');
生成目标div元素的HTMLCollection。
我正在尝试将数组admin1
的每个索引处的字符串添加到每个索引处的每个div的classList中。
for(var i = 0; i < content.length; i++) {
content[i].classList.add(admin1[i]);
}
现在当我console.log content
时,我可以看到添加了新类-但是,它仅显示admin1
数组中所有div的第一个字符串。
我了解到您不能在HTMLCollections上使用for循环,因此我尝试在此处将content
转换为数组:
var contentarr = [...content];
但是当我console.log contentarr
时,我看到它的长度仅为1(索引0)。
(这可能与以下事实有关:最初在html中只有这些div之一,直到它与ng-repeat(angularjs)相乘?)
那么如何将HTMLCollection转换为数组,然后从admin1
数组添加类?
谢谢。
编辑
更多上下文-
var subdivs2 = [];
var subdivs2 = angular.element(document.querySelector('[ng-
controller="mainCtrl"]')).scope().subdivisions2
for(var i = 0; i < subdivs2.length; i++) {
subdivs2[i] = subdivs2[i]["province"];
}
var admin1 = [];
for(var i = 0; i < subdivs2.length; i++) {
admin1[i] = subdivs2[i][0]["name"];
}
我的角度控制器中有一个名为subdivisions2
的嵌套数组。我将名为“ name”的键的所有值放入admin1
数组中。
admin1看起来像这样:
0: "Adrar"
1: "Algiers"
2: "Annaba"
3: "Aïn Defla"
4: "Aïn Témouchent"
5: "Batna"
6: "Biskra"
7: "Blida"
8: "Bordj Bou Arréridj"
9: "Boumerdès"
10: "Bouïra"
11: "Béchar"
12: "Béjaïa"
13: "Chlef"
14: "Constantine"
15: "Djelfa"
16: "El Bayadh"
17: "El Oued"
18: "El Taref"
19: "Ghardaïa"
20: "Illizi"
21: "Jijel"
22: "Khenchela"
23: "Laghouat"
24: "M'Sila"
25: "Mascara"
26: "Mila"
27: "Mostaganem"
28: "Médéa"
29: "Naâma"
30: "Oran"
31: "Ouargla"
32: "Oum el-Bouaghi"
33: "Relizane"
34: "Saïda"
35: "Sidi Bel Abbès"
36: "Skikda"
37: "Souk Ahras"
38: "Sétif"
39: "Tamanghasset"
40: "Tiaret"
41: "Tindouf"
42: "Tipaza"
43: "Tissemsilt"
44: "Tizi Ouzou"
45: "Tlemcen"
46: "Tébessa"
有趣的是,当我查看HTMLCollection时,它在底部显示“ length:47”(与admin1相同的长度)。但是当我把console.log(content.length);它说1.为什么?
答案 0 :(得分:0)
问题是您只有一个循环,并且该循环可以很好地遍历HTML元素,但是当遍历每个HTML元素(仅一次)时,它只会添加当前循环索引。
您需要在此处进行两个循环,一个循环遍历元素,另一个循环在仍位于元素上时遍历样式。
这是一个例子:
let classes = ["big","bold","blue"];
// First, get all the elements you'll want to work with.
// Don't use .getElementsByClassName! Use .querySelectorAll()
let els = document.querySelectorAll(".special");
// You can use regular counting loops on HTMLCollections, but
// Arrays offer more robust looping without you having to manage
// indexes. So, we'll convert the collection to an array:
els = Array.prototype.slice.call(els);
// Loop over the elements array
els.forEach(function(el){
// Now, while we are on just one of the elements,
// start a second loop to go over the string array
classes.forEach(function(cls){
// Add the class to the element that we're currently looping over
el.classList.add(cls);
});
});
.big { font-size:2em; }
.bold { font-weight:bold; }
.blue { color:blue; }
<div class="special">Some Content</div>
<p>Some Content</p>
<div>Some Content</div>
<p class="special">Some Content</p>
<div class="special">Some Content</div>
<p>Some Content</p>
<div>Some Content</div>
<p>Some Content</p>