使用Js创建简单的滑块,当使用带有参数的函数传递给addEventListernet滑块时不起作用但是当放入onclick =" slide(1)"到ID,它工作正常。我做错了什么?
var imgcount = 1;
var imgTotal = 5;
var left = document.querySelector(".left");
var right = document.querySelector(".right");
function slide(x) {
var img = document.getElementById("img");
imgcount = imgcount + x;
img.src = "img/"+ imgcount +".jpg";
}
left.addEventListener('click', slide(-1));
right.addEventListener('click', slide(1))
);
答案 0 :(得分:1)
为了按照您的方式开始,您需要从function
返回slide
:
function slide(x) {
return function(){
var img = document.getElementById("img");
imgcount = imgcount + x;
img.src = "img/"+ imgcount +".jpg";
}
}