javascript - 当“输入”被编程方法更改时,“更改”事件不会调用
问题描述
我有这个示例代码:
//It's my code editable
document.querySelector('#word').addEventListener('change', function() {
document.querySelector('#result').innerHTML = this.value + "!";
});
//-------------------------
//You should not make any changes to this section of the code below,
// as it is an instance and may be similar to another program and elsewhere
// that cannot be identified.
document.querySelector('#fill').addEventListener('click', function() {
document.querySelector('#word').value = "sample text";
});
<input id="word">
<button id="fill">Change it!</button>
<div id="result"></div>
镜像代码:https ://jsfiddle.net/NabiKAZ/t7ps4exj/
当我input
通过键盘或鼠标更改元素的值时,该事件change
运行良好。但是当我使用任何编程方法时,它都不起作用。
例如,当我单击button
此示例代码时,值将被更改,但输入change
事件不会调用。
注意:您假设您不应该对按钮事件单击功能进行任何更改,因为这里的按钮只是一个示例,并且输入值可能会在任何时候以任何方式发生变化!
你对这个问题有什么解决方案?
已编辑:
注 2:我将一小段代码添加Tampermonkey
到一个大型网络应用程序中,我无法更改整个程序中可用的所有代码。input
该程序可能随时以任何方式更改此框的值,我需要通过change
事件或任何最佳实践方法来了解它。
解决方案
最后,我没有找到比监控input
for change 的值更好的方法:
//It's my code editable
var old_word;
setInterval(function() {
var current_word = document.querySelector('#word').value;
if (old_word != current_word) {
document.querySelector('#result').innerHTML = current_word + "!";
old_word = current_word;
}
}, 100);
//-------------------------
//You should not make any changes to this section of the code below,
// as it is an instance and may be similar to another program and elsewhere
// that cannot be identified.
document.querySelector('#fill').addEventListener('click', function() {
document.querySelector('#word').value = "sample text";
});
<input id="word">
<button id="fill">Change it!</button>
<div id="result"></div>
推荐阅读
- php - Docker php DPO 到 MariaDB - 错误:找不到驱动程序
- python - 如何将带有'for'循环的打印输出保存为Python中的数组变量?
- javascript - 访问 cart.order_items.length 给出 TypeError: Cannot read property 'length' of undefined
- java - 方法完成后变量返回null
- javascript - 如何修复“UnhandledPromiseRejectionWarning:ReferenceError:内容未定义”
- r - 在 Stan 中哪个更有效?
- java - 我的 PostImage 没有在 recycleview 中显示我的文本和个人资料图片反映在 firebase 数据库中,postimage 没有反映
- image - 参数化 SVG 图像失败
- c# - C#中的二分查找
- xpath - 在 Coinmarketcap 上的 Scrapy 中为 response.xpath 或 response.css 找到正确的选择器时出现问题