图像数组。未捕获的 TypeError:无法将属性“src”设置为 null [重复]
2017-11-16
765
第一次摆弄数组。尝试循环浏览图像数组,单击下一个按钮时出现“未捕获类型错误:无法将属性“src”设置为 null”。我以为这只是 id 不匹配之类的简单问题,但我没有发现任何类似的问题。
var target = document.getElementById('target');
var counter = 0;
var imageArray = [
"megatron.png",
"starscream.jpg",
"soundwave.jpg",
"shockwave.jpg",
"devastator.jpg",
"astrotrain.jpg",
"blitzwing.jpg",
"thrust.jpg",
"rumble.png",
"ravage.jpg",
"laserbeak.jpg",
"reflector.jpg"
];
function next() {
counter = counter + 1;
if (counter > imageArray.length -1) {
counter = 0;
}
target.src = imageArray[counter];
}
</!DOCTYPE html>
<html>
<head>
<title>Image Array</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./image-array.css">
<script src="image-array.js"></script>
</head>
<body>
<h1 class="center">Image Array</h1>
<div id="page" class="center">
<div id="socket" class="center">
<img src="megatron.png" id="target">
</div>
<div id="switchplate" class="center">
<button onclick="next()" id="next">Next</button>
</div>
</div>
</body>
</html>
2个回答
这是您的代码的工作示例。请检查
var counter = 0;
var imageArray = [
"https://doodles.google.ca/d4g/images/splashes/featured.png", "https://vignette.wikia.nocookie.net/logopedia/images/a/aa/Google_Assistant.png/revision/latest?cb=20170815132456",
"http://st1.bgr.in/wp-content/uploads/2017/07/google-search.jpg"
];
function next() {
counter = counter + 1;
if (counter > imageArray.length -1) {
counter = 0;
}
target.src = imageArray[counter];
}
</!DOCTYPE html>
<html>
<head>
<title>Image Array</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./image-array.css">
<script src="image-array.js"></script>
</head>
<body>
<h1 class="center">Image Array</h1>
<div id="page" class="center">
<div id="socket" class="center">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLxmBuSqBLEVe6FZkt8CK7GxewFiDHOihhgod4ncC8H0hPVV6w" style="width:100px;height:100px;" id="target" >
</div>
<div id="switchplate" class="center">
<button onclick="next()" id="next">Next</button>
</div>
</div>
</body>
</html>
Sandeep P Pillai
2017-11-16
该问题是由于在 head 标签中加载了
<script src="image-array.js"></script>
造成的。
当上述脚本加载完成后,它将运行此语句
var target = document.getElementById('target');
此时 DOM 尚未准备好,并且没有 id 为
因此会引发错误。
删除脚本标签,并在关闭 body 标签之前添加它
target
<body>
// rest of the DOM
<script src="image-array.js"></script>
</body>
brk
2017-11-16