[英]unable to iterate on HtmlCollection
I have an issue with a simple code 我有一个简单的代码问题
var x = document.getElementsByTagName("th");
var plop = Array.prototype.slice(x);
console.log(x);
console.log(x.length);
console.log(plop);
output 产量
[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 []
Why does I see lenght 7 here and the x.length gives 0 ? 为什么我在这里看到长度为7,而x.length为0?
Thanks in advance 提前致谢
update : I set the code in 更新:我在设置代码
$scope.$on('$viewContentLoaded', function(){
}
And it works now. 现在就可以了。 I'm not yet able to set an onclick method but it progress ^^
我尚无法设置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");
};
}
};
You are missing the .call()
when you're trying to make an array copy from the HTMLCollection
. 当您尝试从
HTMLCollection
制作数组副本时,您缺少.call()
。 Instead of this: 代替这个:
var x = document.getElementsByTagName("th");
var plop = Array.prototype.slice(x);
You can do this: 你可以这样做:
var x = document.getElementsByTagName("th");
var plop = Array.prototype.slice.call(x);
console.log(plop);
Note: you don't need to make an array copy just to iterate over it. 注意:您不需要仅复制数组副本即可对其进行迭代。 You can iterate an HTMLCollection directly:
您可以直接迭代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.