图像数组。未捕获的TypeError:无法设置属性' src'为null

时间:2017-11-16 03:37:37

标签: javascript arrays dom

第一次弄乱阵列。尝试在图像数组中循环,获取" Uncaught TypeError:无法设置属性' src' of 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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

以下是您的代码的工作示例。请检查

&#13;
&#13;
Maybe
&#13;
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];
}
&#13;
&#13;
&#13;

答案 1 :(得分:2)

问题是因为<script src="image-array.js"></script>的加载位于head标记中。

加载上述脚本后,它将运行此语句

var target = document.getElementById('target');

那时DOM还没有准备好,没有名为target

的元素

所以它抛出错误。

删除脚本标记并在关闭正文标记

之前添加它
<body>
  // rest of the DOM
<script src="image-array.js"></script>
</body>