首页 > 解决方案 > 当“输入”被编程方法更改时,“更改”事件不会调用

问题描述

我有这个示例代码:

//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事件或任何最佳实践方法来了解它。

标签: javascripthtmlevents

解决方案


最后,我没有找到比监控inputfor 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>

镜像代码:https ://jsfiddle.net/NabiKAZ/t7ps4exj/13/


推荐阅读