单击按钮以使用“addEventListener

时间:2018-01-24 23:28:19

标签: javascript

我想要实现的是当我点击id =“black”的div时         图像从一个图像变为另一个图像。但我不知道是什么         做

var image = document.getElementById("change");
var black = document.getElementById("black");

black.addEventListener("click", changeBlack());

function changeBlack() {
  if (image.src == "img/backpack.jpeg") {
    image.src = "img/back.jpeg";
  } else {
    image.src = "img/backpack.jpeg";
  }
}
<div class="product">
  <img class="product__img" src="img/backpack.jpeg" alt="images" id="change">
  <h2 class="heading-2">Hugger 30L</h2>
  <p class="paragraph">Smart carry-on backpack</p>
  <h4 class="text-price">Kr 1599</h4>

  <div class="product__colors">
    <div class="product__colors--black " id="black"></div>
    <div class="product__colors--white"></div>
    <div class="product__colors--green"></div>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

您应该删除括号(),将是:

black.addEventListener("click", changeBlack );

而不是:

black.addEventListener("click", changeBlack() );
___________________________________________^^

答案 1 :(得分:0)

我会在函数内声明图像。

function changeBlack()
{
    var image = document.getElementById("change");
    if (image.src == "img/backpack.jpeg")
    {
        image.src = "img/back.jpeg";
    }
    else
    {
        image.src = "img/backpack.jpeg";
    }
}