0

我对一个简单的代码有疑问

    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 []

为什么我在这里看到 lenght 7 而 x.length 给出 0 ?

提前致谢

更新:我将代码设置为

$scope.$on('$viewContentLoaded', function(){
}

它现在有效。我还不能设置 onclick 方法,但它正在进步 ^^

4

2 回答 2

0
$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");
            };
        }
};
于 2015-02-02T20:01:22.730 回答
0

当您.call()尝试从HTMLCollection. 而不是这个:

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]);
}
于 2015-02-02T20:15:08.353 回答