正如您在下面的代码部分中看到的,当您单击一个按钮时,字段中的文本会发生更改但事件不会被触发(并且它不会运行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);
}Run Code Online (Sandbox Code Playgroud)
<input type=text id="query">
<button id="change-text">Change the text programmatically</button>
<button id="clear">Clear</button>Run Code Online (Sandbox Code Playgroud)
viz*_*viz 10
尝试这个手动调度事件,请参阅EventTarget.dispatchEvent():
inputField.dispatchEvent(new Event("input"))
Run Code Online (Sandbox Code Playgroud)
来自React 文档
React 希望听到这个
input事件
所以input在设置值后触发事件。这是如何触发。
最终代码是:
var event = new Event('input', {
'bubbles': true,
'cancelable': true
});
inputElement.value = '0.2'
inputElement.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)