gpt4 book ai didi

javascript - 无法读取 null 的属性 'id' - JS 错误

转载 作者:行者123 更新时间:2023-11-30 08:35:26 24 4
gpt4 key购买 nike

我有以下 html 代码:

<!DOCTYPE html>
<html>
<head>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
</body>
</html>

然而在控制台中,当它到达第 9 行时我收到一个错误,它说“null 的类型不存在”,但显然 div 的 id 必须存在,因为我已经将它声明为 id body 。这怎么可能?

最佳答案

加载脚本时不会加载 html 元素,因此在执行 javascript 时不存在。更改代码的顺序将解决问题:

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</body>
</html>

关于javascript - 无法读取 null 的属性 'id' - JS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31767354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com