如您在下面的代码片段中所看到的,一旦单击其中一个按钮,字段中的文本会更改,但是事件不会触发(也不会运行alertTextInput()方法),当您直接在文本字段下键入文本时,预期的事件将被触发。
如何通过使用代码或使用更改文本并触发事���的方法手动激活事件?谢谢!
const changeTextButton = document.querySelector("#change-text");
const clearButton = document.querySelector("#clear");
const inputField = document.querySelector("#query");
changeTextButton.addEventListener("click", changeText);
clearButton.addEventListener("click", clear);
inputField.addEventListener("input", alertTextInput);
function changeText() {
inputField.value = "Demo Text!!";
inputField.dispatchEvent(new Event("input"))
}
function clear() {
inputField.value = "";
inputField.dispatchEvent(new Event("input"))
}
function alertTextInput() {
alert(inputField.value);
}
<input type=text id="query">
<button id="change-text">Change the text programmatically</button>
<button id="clear">Clear</button>
inputField.value = "Demo Text!!";
更改文本后运行alertTextInput()
- 不幸的是,这不被认为是输入事件监听器的事件。我认为你需要手动调用它。 - adprocas