将参数传递给addEventListener

时间:2016-02-22 14:15:55

标签: javascript

使用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))

);

1 个答案:

答案 0 :(得分:1)

为了按照您的方式开始,您需要从function返回slide

function slide(x) {
   return function(){
      var img = document.getElementById("img");
      imgcount = imgcount + x;
      img.src = "img/"+ imgcount +".jpg";
   }
}