我试图用js选中一个复选框并检测到更改,但是onchange事件未检测到更改,而这在视觉上已更改。 (对不起,英语不好,我是法国人) 这是一个示例:
document.querySelector("#checkbox").onchange = (e) => {
let checked = e.target.checked;
if (checked) {
console.log("checked !");
} else {
console.log("unchecked...");
}
}
document.querySelector("#buttonOn").onclick = (e) => {
document.querySelector("#checkbox").checked = true;
}
document.querySelector("#buttonOff").onclick = (e) => {
document.querySelector("#checkbox").checked = false;
}
<button id="buttonOn">On</button>
<button id="buttonOff">Off</button>
<input type="checkbox" name="" id="checkbox">
答案 0 :(得分:2)
您需要在单击按钮时触发事件
document.querySelector("#checkbox").onchange = (e) => {
let checked = e.target.checked;
if (checked) {
console.log("checked !");
} else {
console.log("unchecked...");
}
}
// Create new change event
var event = new Event('change');
document.querySelector("#buttonOn").onclick = (e) => {
document.querySelector("#checkbox").checked = true;
// Trigger onchange
document.querySelector("#checkbox").dispatchEvent(event);
}
document.querySelector("#buttonOff").onclick = (e) => {
document.querySelector("#checkbox").checked = false;
// Trigger onchange
document.querySelector("#checkbox").dispatchEvent(event);
}
<button id="buttonOn">On</button>
<button id="buttonOff">Off</button>
<input type="checkbox" name="" id="checkbox">