我是JavaScript的初学者,我似乎无法使我的代码正常工作。我的任务早就该完成了,似乎无法让goForward()“ >>>”和goBackward()“ <<>>”按钮时,它将显示数组中的下一个图像。与“ <<>>”显示4张图片,然后返回到第一张图片。 “ <<https://codepen.io/oshitaiya/pen/mddNWaq enter code here
。这是我的分配要求https://docs.google.com/document/d/12IcETUGbgxC4jKBs0BK8HHLrjB_35mVlqK1kGTVIg-Y/edit?usp=sharing
我已经用changeImage
函数替换了两个函数,从而在某处编辑了您的代码。
var kawaii = ["https://media.giphy.com/media/3oKIPy2hjnheNraWwo/giphy.gif",
"https://media1.giphy.com/media/l3UcgEIw80eyb36kU/source.gif",
"https://media1.giphy.com/media/xTiN0mN3wxWO0MDuGk/source.gif",
"https://media2.giphy.com/media/3o6EhPDMjaDP5UC4ZW/source.gif",
"https://66.media.tumblr.com/3b9394556e6e0c6271594be2339c5d21/tumblr_nqkmdcPzbd1qak30bo1_500.gifv"]
var index = 0
function changeImage() {
index = index < 0 ? kawaii.length - 1 : index;
index = index === kawaii.length - 1 ? 0 : index;
document.getElementById("imgid").src = kawaii[index];
index++;
};
body {
background-color: #a3d5d3;
}
<h1>Image Gallery</h1>
<img id="imgid"/><br>
<input type="button" onclick="changeImage()" value="<<<<"/>
<input type="button" onclick="changeImage()" value=">>>>"/>
或者如果您想保留两个功能:
var kawaii = ["https://media.giphy.com/media/3oKIPy2hjnheNraWwo/giphy.gif",
"https://media1.giphy.com/media/l3UcgEIw80eyb36kU/source.gif",
"https://media1.giphy.com/media/xTiN0mN3wxWO0MDuGk/source.gif",
"https://media2.giphy.com/media/3o6EhPDMjaDP5UC4ZW/source.gif",
"https://66.media.tumblr.com/3b9394556e6e0c6271594be2339c5d21/tumblr_nqkmdcPzbd1qak30bo1_500.gifv"]
var index = 0
function changeImage() {
index = index < 0 ? kawaii.length - 1 : index;
index = index === kawaii.length - 1 ? 0 : index;
document.getElementById("imgid").src = kawaii[index];
index++;
};
function goBackward() {
changeImage();
}
function goForward() {
changeImage();
}
body {
background-color: #a3d5d3;
}
<h1>Image Gallery</h1>
<img id="imgid"/><br>
<input type="button" onclick="goBackward()" value="<<<<"/>
<input type="button" onclick="goForward()" value=">>>>"/>
通过保留您所拥有的。在附加之前运行所有逻辑。
var kawaii = ["https://media.giphy.com/media/3oKIPy2hjnheNraWwo/giphy.gif",
"https://media1.giphy.com/media/l3UcgEIw80eyb36kU/source.gif",
"https://media1.giphy.com/media/xTiN0mN3wxWO0MDuGk/source.gif",
"https://media2.giphy.com/media/3o6EhPDMjaDP5UC4ZW/source.gif",
"https://66.media.tumblr.com/3b9394556e6e0c6271594be2339c5d21/tumblr_nqkmdcPzbd1qak30bo1_500.gifv"]
var index = 0
function goForward(){
index++
if (index > kawaii.length - 1) {
index = 0
}
document.getElementById("imgid").src = kawaii[index]
}
function goBackward(){
index--
if (index < 0) {
index = kawaii.length - 1
}
document.getElementById("imgid").src = kawaii[index]
}