[英]Howto trigger input event programmatically on input text field?
As you can see in the code section below, once you click on one the buttons the text in the field changes but the event does not get fired (and it does not run alertTextInput() method) , when you type text directly under the text field the event is triggered as expected. 正如您在下面的代码部分中所看到的,当您单击一个按钮时,字段中的文本会发生更改但事件不会被触发(并且它不会运行alertTextInput()方法) ,当您直接在文本下键入文本时字段事件按预期触发。
How can I activate the event manually by using a code or using a method that changes the text and triggers the event? 如何通过使用代码或使用更改文本并触发事件的方法手动激活事件? thank you!
谢谢!
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>
尝试这个手动调度事件,请参阅EventTarget.dispatchEvent() :
inputField.dispatchEvent(new Event("input"))
If I understand correctly you want the input text to change AND the alert to appear when clicking "change" button. 如果我理解正确,您希望输入文本更改,并在单击“更改”按钮时显示警报。 As the changeText() function just changes the text you should not expect an alert to appear.
由于changeText()函数只是更改文本,因此您不应期望出现警报。
You could just add the alertTextInput() function to the bottom of changeText(). 您可以将alertTextInput()函数添加到changeText()的底部。
function changeText() {
inputField.value = "Demo Text!!";
alertTextInput();
}
React expects to hear the
input
eventReact希望听到
input
事件
So trigger the input
event after set the value. 因此在设置值后触发
input
事件。 This is how to trigger . 这是如何触发的 。
The Final code is: 最终的代码是:
var event = new Event('input', {
'bubbles': true,
'cancelable': true
});
inputElement.value = '0.2'
inputElement.dispatchEvent(event);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.