javascript事件仅触发一次

时间:2019-06-08 19:05:51

标签: javascript css

我下面的代码有问题。 该代码应处理滑块,并在img为 单击,它只能运行一次。

将onClick事件更改为

    document.getElementById("left").onclick = function(){
        console.log("0");
    }

它工作正常,但是当我还原时,它不会多次更改滑块

摘要:

var index = 0;

document.getElementById("left").onclick = function(){
  console.log("0");
}

document.getElementById("left").onclick = function(){
  var slider = document.getElementsByClassName("slider");
  slider[index].style.display = "none";
  if(index == 0){ index = slider.length;}
  slider[--index].style.display = "block";
}

document.getElementById("right").onclick = function(){
  var slider = document.getElementsByClassName("slider");
  slider[index].style.display = "none";
  if(index >= slider.length){ index = 0;}
  slider[++index].style.display = "block";
};
<div class="slider" style="display: block">
  <div id = "left"><img src="Images/arrow-left.png" alt=""></div>
  <div class="text">
    <h2>welcome to the <span>classic</span></h2>
    <p>Lorem ipsum is a name for a common type of placeholder text. Also known as filler or dummy text, this is simply copy that serves to fill a space</p>
  </div>
  <div id = "right"><img src="Images/arrow-right.png" alt=""></div>
</div>

1 个答案:

答案 0 :(得分:2)

谢谢大家,问题在于我为多个div赋予了相同的ID,这使onclick事件仅触发一次(仅针对第一个div)