[英]unable to iterate on HtmlCollection
我有一個簡單的代碼問題
var x = document.getElementsByTagName("th");
var plop = Array.prototype.slice(x);
console.log(x);
console.log(x.length);
console.log(plop);
產量
[item: function, namedItem: function]
0: th.fc-day-header.fc-sun.fc-widget-header.fc-first
1: th.fc-day-header.fc-mon.fc-widget-header
2: th.fc-day-header.fc-tue.fc-widget-header
3: th.fc-day-header.fc-wed.fc-widget-header
4: th.fc-day-header.fc-thu.fc-widget-header
5: th.fc-day-header.fc-fri.fc-widget-header
6: th.fc-day-header.fc-sat.fc-widget-header.fc-last
length: 7__proto__: HTMLCollection
controller.js:309 0
controller.js:310 []
為什么我在這里看到長度為7,而x.length為0?
提前致謝
更新:我在設置代碼
$scope.$on('$viewContentLoaded', function(){
}
現在就可以了。 我尚無法設置onclick方法,但它會進展^^
$scope.$on('$viewContentLoaded', function(){
var x = document.getElementsByTagName("th");
var arr = Array.prototype.slice.call(x);
console.log(arr);
for (var i = 0; i < arr.length; i++) {
// console.log("iterate");
console.log(arr[i]);
arr[i].onclick = function(){
console.log("lol");
};
}
};
當您嘗試從HTMLCollection
制作數組副本時,您缺少.call()
。 代替這個:
var x = document.getElementsByTagName("th");
var plop = Array.prototype.slice(x);
你可以這樣做:
var x = document.getElementsByTagName("th");
var plop = Array.prototype.slice.call(x);
console.log(plop);
注意:您不需要僅復制數組副本即可對其進行迭代。 您可以直接迭代HTMLCollection:
var items = document.getElementsByTagName("th");
for (var i = 0; i < items.length; i++) {
console.log(items[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.