我刚开始学习 JavaScript。我只想构建一个图像轮播,但在第一行出现错误:
Uncaught TypeError: Cannot read property 'getAttribute' of null
js:
function changeImage(){
var imageSrc=document.getElementById("image").getAttribute("src");
}
changeImage();
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="hello.js"></script>
<title></title>
</head>
<body>
<div id="button_left">
<img id ="left" src="left.png">
</div>
<div id="button_right">
<img id ="right" src="right.png">
</div>
<div class="container">
<img id ="image" src="1.jpg">
</div>
<div id="result"></div>
</body>
</html>
最佳答案
问题是因为脚本中的 document.getElementById("image")
甚至在加载目标元素之前就被调用了,它返回 undefined
/null
。然后在 undefined
/null
对象上调用链接的 .getAttribute("src")
。
许多可能的解决方案之一是在页面加载后执行函数。将脚本中的代码更改为以下内容:
window.onload = 函数 () {
var imageSrc=document.getElementById("image").getAttribute("src");
}
in hello.js
将使脚本在页面完全加载后执行。
其他答案涵盖了解决此问题的其他几种方法。
关于javascript - 未捕获的类型错误 : Cannot read property 'getAttribute' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542312/