我仍在学习Javacript。这是我在家中的第一个任务。但是,即使我尝试按照说明逐步进行操作,我似乎也无法使代码正常工作。我需要创建一个幻灯片,当我单击该按钮时,将出现一个新图像,直到循环回到第一个图像为止。我检查了所有内容,但仍然无法弄清楚自己做错了什么。如果您能解释和帮助,我将不胜感激。
<body onload="startup();">
<center>
<img id="banner" src="images/bangkok_thailand.jpg">
<br>
<button onclick="cycle();">Click Here to Change Image</button>
<script>
var imgArray = new Array();
var index = 0;
function cycle() {
document.getElementById("banner").src = imgArray[index].src;
index = index + 1;
if (index > 5 ) {
index = 0;
}
return;
}
function startup()
{
imgArray[0] = new Image;
imgArray[1] = new Image;
imgArray[2] = new Image;
imgArray[3] = new Image;
imgArray[4] = new Image;
imgArray[5] = new Image;
imgArray[0]. src="images/bangkok_thailand.jpg";
imgArray[1]. src="images/paris_france.jpg";
imgArray[2]. src="images/seoul_southkorea.jpg";
imgArray[3]. src="images/tokyo_japan.jpg";
imgArray[4]. src="images/istanbul_turkey.jpg";
imgArray[5]. src="images/amsterdam_netherlands";
}
//cycle();
return;
</script>
</center>
答案 0 :(得分:1)
首先,您在脚本上有一个流浪return
-这导致该函数无法加载。其次,在imgArray[x].
和src
之间有一个空格。解决第一个问题,它应该可以工作,第二个问题是可选的,但您也要修复它。
我在下面的演示中使用https://picsum.photos/。希望这会有所帮助
<body onload="startup();">
<center>
<img id="banner" src="https://picsum.photos/400/300/?random">
<br>
<button onclick="cycle();">Click Here to Change Image</button>
<script>
var imgArray = new Array();
var index = 0;
function cycle() {
document.getElementById("banner").src = imgArray[index].src;
index = index + 1;
if (index > 5) {
index = 0;
}
return;
}
function startup() {
imgArray[0] = new Image;
imgArray[1] = new Image;
imgArray[2] = new Image;
imgArray[3] = new Image;
imgArray[4] = new Image;
imgArray[5] = new Image;
imgArray[0].src = "https://picsum.photos/350/300/?random";
imgArray[1].src = "https://picsum.photos/300/300/?random";
imgArray[2].src = "https://picsum.photos/250/300/?random";
imgArray[3].src = "https://picsum.photos/200/300/?random";
imgArray[4].src = "https://picsum.photos/150/300/?random";
imgArray[5].src = "https://picsum.photos/100/300/?random";
}
</script>
</center>
</body>