我正在尝试为幻灯片显示编写动态代码。我已多次看过它,我认为一切都是正确的,但它不起作用。我只是找不到我有错误的地方。我希望有人能告诉我出了什么问题:
<button type="button" id="back"><<</button>
<button type="button" id="forward">>></button>
<img id="photo" src="http://photo.interpressnews.ge/img/image1/b37065d8bf0bd9e25d5bcb3c144b0269.jpg" width="200 height="200>
和Javascript:
var photos = new Array("http://photo.interpressnews.ge/img/image1/b37065d8bf0bd9e25d5bcb3c144b0269.jpg", "http://photo.interpressnews.ge/img/image1/c81dae9175d056aa243a5a0e56b3c111.jpg", "http://photo.interpressnews.ge/img/image1/5ff96384ddf214ef33706ffdb922b710.jpg");
var imgnumber = 0;
var imgleng = photos.length - 1;
var img = document.getElementById("photo");
var current = photos.indexOf(img.src);
var nextindex;
var back = document.getElementById("back");
var forward = document.getElementById("forward");
back.addEventListener('click', toggleImage('back'));
forward.addEventListener('click', toggleImage('forward'));
function toggleImage(direction) {
if(direction == 'forward'){
nextindex = current != photos.length - 1 ? current + 1 : 0;
} else {
nextindex = current != 0 ? current - 1 : photos.length - 1;
}
img.src = photos[nextindex];
}
答案 0 :(得分:0)
问题与onclick事件有关。您正在调用该函数,而不是将其绑定到事件侦听器。带参数'back'或'forward'的函数调用必须在函数内。这是更正后的代码:
var photos = new Array("http://photo.interpressnews.ge/img/image1/b37065d8bf0bd9e25d5bcb3c144b0269.jpg", "http://photo.interpressnews.ge/img/image1/c81dae9175d056aa243a5a0e56b3c111.jpg", "http://photo.interpressnews.ge/img/image1/5ff96384ddf214ef33706ffdb922b710.jpg");
var imgnumber = 0;
var imgleng = photos.length - 1;
var img = document.getElementById("photo");
var current = photos.indexOf(img.src);
var nextindex;
var back = document.getElementById("back");
var forward = document.getElementById("forward");
back.addEventListener('click', function(){toggleImage('back')});
forward.addEventListener('click', function(){toggleImage('forward')});
function toggleImage(direction) {
if(direction == 'forward'){
current = current != photos.length - 1 ? current + 1 : 0;
} else {
current = current != 0 ? current - 1 : photos.length - 1;
}
img.src = photos[current];
}