在一个Angular 应用程序中,我使用普通JS通过类名Code获取元素:
var testElements = document.getElementsByClassName("project-link");
console.log(testElements);
这样打印:
[item: function, namedItem: function]
0: a.project-link.ng-binding
1: a.project-link.ng-binding
...
30: a.project-link.ng-binding
length: 32
__proto__: HTMLCollection
但是,如果我尝试单独打印一个项目,则返回null:
console.log(testElements.item(4));
null
我不明白这个代码有什么问题,我也试过Array.prototype.filter.call的功能,它也不工作。有什么想法吗?
3条答案
按热度按时间esyap4oy1#
我通过在窗口加载函数中添加我的代码修复了这个错误:
mbjcgjjk2#
这是因为JS代码是在HTML中的dom树构建之前加载的,此时页面还是空的,所以返回null。
使用窗口.onload
wribegjk3#
试试这个,可能会有帮助~
我不知道为什么,但它对我很有效。