繁体   English   中英

EventListener 中的更改事件不会触发

[英]change event in EventListener doesnt trigger

所以我做了一个小版本的我的问题。 在这里,我将文本添加到输入元素中。 但是当它被添加时,它不会触发事件监听器。

 function testFunction() { document.getElementById("testInput").addEventListener("change", () => { console.log("hi"); }); } function testText() { document.getElementById("testInput").value = "Hello there"; } testFunction();
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="styles.css" /> <title>Document</title> </head> <body> <script></script> <button onclick="testText()" style="height: 20px"></button> <input id="testInput" /> <script src="script.js"></script> </body> </html>

您需要手动创建事件并使用dispatchEvent()方法将事件触发到目标元素。

 function testFunction() { document.getElementById("testInput").addEventListener("input", () => { console.log("hi"); }); } function testText() { document.getElementById("testInput").value = "Hello there"; let event = new Event("input"); document.getElementById("testInput").dispatchEvent(event); } testFunction();
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="styles.css" /> <title>Document</title> </head> <body> <script></script> <button onclick="testText()" style="height: 20px"></button> <input id="testInput" /> <script src="script.js"></script> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM