复选框修改 javascript 的 onChange 事件
onChange event with javascript modifications of checkbox
我试图用 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">
您需要在点击按钮时触发事件
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">
我试图用 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">
您需要在点击按钮时触发事件
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">