小编Sag*_*dav的帖子

如何在输入文本字段上以编程方式触发输入事件?

正如您在下面的代码部分中看到的,当您单击一个按钮时,字段中的文本会发生更改但事件不会被触发(并且它不会运行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)

javascript

4
推荐指数
2
解决办法
4650
查看次数

标签 统计

javascript ×1