JavaScript 图像显示不起作用

JavaScript image displaying not working

本文关键字:不起作用 显示 图像 JavaScript      更新时间:2023-09-26

我在HTML文档中嵌入了一些JavaScript代码。当我运行它时,它不显示图像。代码附在下面,任何帮助不胜感激。

var images = new Array ("red.JPG");
function getCurrentImageIndex() {
	return images.indexOf(document.getElementById("image").src);
}
function next() {
	nextImage = (getCurrentImageIndex() + 1) % images.length;
	document.getElementById("image").src = images[nextImage];
}
function prev() {
	nextImage = (getCurrentImageIndex() - 1 + images.length) % images.length;
	document.getElementById("image").src = images[nextImage];
}
<html>
  <body>
<script>
  
  //script here
</script>
<img id="image" />
<button onCLick="next()">press me</button> 
</body>  
</html>

如果我使用绝对图像路径,对我有用:

var images = [
   "https://cdn.sstatic.net/stackoverflow/img/sprites.png", 
   "https://www.gravatar.com/avatar/06caf7997bde5d38c5aee0e051206614?s=48&d=identicon&r=PG"
];
function getCurrentImageIndex() {
	return images.indexOf(document.getElementById("image").src);
}
function next() {
	nextImage = (getCurrentImageIndex() + 1) % images.length;
	document.getElementById("image").src = images[nextImage];
}
function prev() {
	nextImage = (getCurrentImageIndex() - 1 + images.length) % images.length;
	document.getElementById("image").src = images[nextImage];
}
<html>
  <body>
<script>
  
  //script here
</script>
<img id="image" />
<button onCLick="next()">press me</button> 
</body>  
</html>

我用你的代码快速创建了一个笔。它似乎有效。我唯一更改的是图像的网址。

var images = new Array ("http://cdn.digital.guide/2015/09/test.gif", "http://xiostorage.com/wp-content/uploads/2015/10/test.png");

由于您为图像使用相对 URL,因此请确保它们正确无误。就像现在一样,图像应该在html文件的同一文件夹中。