在隐藏复选框上添加更改事件

时间:2016-10-26 10:08:42

标签: javascript javascript-events

我试图捕捉更改事件,或者至少点击复选框上的事件。我已经读到了"可见性:隐藏"或"显示:无",事件未被触发。然后我将eventListener添加到标签,但它似乎也不起作用。无法理解如何工作



document.addEventListener("DOMContentLoaded", function() {
  var gameCount = document.getElementsByClassName("innerCount")[0];
  var checkLabel = document.querySelector("input[type=checkbox] + label");
  checkLabel.addEventListener("onclick", function() {
    if (checkLabel.checked) {
      gameCount.innerHTML = "--";
      console.log("turnOn");
    } else {
      gameCount.innerHTML = "";
      console.log("turnOff");
    }
  })
});

.checkbox > input[type=checkbox] {
  visibility: hidden;
}
.checkbox {
  display: inline-block;
  position: relative;
  width: 60px;
  height: 30px;
  border: 2px solid #424242;
}
.checkbox > label {
  position: absolute;
  width: 30px;
  height: 26px;
  background-color: #a50005;
  cursor: pointer;
}
.checkbox > input[type=checkbox]:checked + label {
  right: 28px;
}

<div id="switcher">
  <span class="labels">ON</span>
  <div class="checkbox">
    <input id="checkMe" type="checkbox">
    <label for="checkMe"></label>
  </div>
  <span class="labels">OFF</span>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

这是因为addEventListener onClick不存在。请尝试使用click

&#13;
&#13;
document.addEventListener("DOMContentLoaded", function() {
  var gameCount = document.getElementsByClassName("innerCount")[0];
  var checkLabel = document.querySelector("input[type=checkbox] + label");
  checkLabel.addEventListener("click", function() {
    if (checkLabel.checked) {
      console.log("turnOn");
    } else {
      console.log("turnOff");
    }
  })
});
&#13;
.checkbox > input[type=checkbox] {
  visibility: hidden;
}
.checkbox {
  display: inline-block;
  position: relative;
  width: 60px;
  height: 30px;
  border: 2px solid #424242;
}
.checkbox > label {
  position: absolute;
  width: 30px;
  height: 26px;
  background-color: #a50005;
  cursor: pointer;
}
.checkbox > input[type=checkbox]:checked + label {
  right: 28px;
}
&#13;
<div id="switcher">
  <span class="labels">ON</span>
  <div class="checkbox">
    <input id="checkMe" type="checkbox">
    <label for="checkMe"></label>
  </div>
  <span class="labels">OFF</span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用change事件侦听器获取复选框字段。

document.addEventListener("DOMContentLoaded", function() {
  var gameCount = document.getElementsByClassName("innerCount")[0];
  var checkLabel = document.querySelector("input[type=checkbox]");
  checkLabel.addEventListener("change", function() {
    if (checkLabel.checked) {
      gameCount.innerHTML = "--";
      console.log("turnOn");
    } else {
      gameCount.innerHTML = "";
      console.log("turnOff");
    }
  })
});