angularjs HTMLCollection.item()函数返回空值

bvk5enib  于 2022-10-31  发布在  Angular
关注(0)|答案(3)|浏览(236)

在一个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的功能,它也不工作。有什么想法吗?

esyap4oy

esyap4oy1#

我通过在窗口加载函数中添加我的代码修复了这个错误:

window.addEventListener("load", function(event) {
   // your code ....
 });
mbjcgjjk

mbjcgjjk2#

这是因为JS代码是在HTML中的dom树构建之前加载的,此时页面还是空的,所以返回null。
使用窗口.onload

<script >
    window.onload = function() {
        const testElement=document.getElementsByClassName("project-link").item(0);
        console.log(testElement);
    }
</script>
wribegjk

wribegjk3#

setTimeout(() => {
  console.log(testElements.item(4));
}, 0);

试试这个,可能会有帮助~
我不知道为什么,但它对我很有效。

相关问题