我试图在Javascript中使用Ajax和JQuery创建一个图片库。我在VSC中创建了一个文件夹名为images;里面我有5选择图像。不幸的是,一旦我点击"下一步"one_answers";previous"按钮,图像不显示。在控制台中它说照片是未定义的。关于如何解决这个问题,有什么想法吗?我将非常感谢你的帮助,因为我对这一切都很陌生!下面是我的HTML和JS代码:
<div id="content">
<div id="picture">
<img id="pic" src="images/image1.jpg">
</div>
</div>
<div id="buttons">
<button id="previous" type="button" class="BUTTON_AUJ">Previous</button>
<button id="update" type="button" class="BUTTON_AUJ">Update</button>
<button id="next" type="button" class="BUTTON_AUJ">Next</button>
</div>
'use strict';
$(document).ready(function () {
var max_index = null, min_index = 0;
var timeID = null;
var index = 0;
var files = [];
function changePicture(pics){
$("#pic").attr("src", "images/" + pics);
$("#picture").hide().fadeIn("slow");
}
function loadImages() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
files = JSON.parse(this.responseText).files;
max_index = files.length - 1;
changePicture(files[index]);
rotating(files[min_index]);
}
};
xhttp.open("GET", "file.html", true);
xhttp.send();
}
function nextPicture(){
if (index < max_index)
index++;
else
index = min_index;
changePicture(files[index]);
rotating(files[index]);
}
function previousPicture() {
if (index > min_index)
index--;
else
index = max_index;
changePicture(files[index]);
rotating(files[index]);
}
function rotating(filename){
var interval = filename.split("_")[1].replace(".jpg", "") * 1000;
if (timeID) {
clearTimeout(timeID);
timeID = null;
}
timeID = setTimeout(nextPicture, interval);
}
function main(){
loadImages();
}
main();
$("#next").click(function () {
nextPicture();
});
$("#previous").click(function () {
previousPicture();
});
$("update").click(function(){
index = 0;
loadImages();
});
});
考虑下面的例子:
小提琴:https://jsfiddle.net/Twisty/0ku35r7b/