我试图捕捉更改事件,或者至少点击复选框上的事件。我已经读到了"可见性:隐藏"或"显示:无",事件未被触发。然后我将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;
答案 0 :(得分:2)
这是因为addEventListener
onClick
不存在。请尝试使用click
:
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;
答案 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");
}
})
});