当通过编程方法更改输入时,不会调用change事件

时间:2019-10-16 23:01:33

标签: javascript html events

我有以下示例代码:

//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添加到大型Web应用程序中,因此无法更改程序中所有可用的代码。该程序可以随时通过任何方式更改此input框的值,我需要通过change事件或任何最佳做法方法来了解它。

2 个答案:

答案 0 :(得分:0)

最后,我没有发现比监视input的值有什么更好的方法了:

//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/

答案 1 :(得分:-3)

您可以重新定义HTMLInputElememnt的值设置器

Object.defineProperty(HTMLInputElement.prototype, 'value', {
  set: function (value) { 
     this.setAttribute('value', value)
     updateHandler();
  }
});