本文介绍了JavaScript 更改输入值时的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

元素的值通过 JavaScript 代码更改时会发生什么事件?例如:

What is the event when an <input> element's value is changed via JavaScript code? For example:

$input.value = 12;

input 事件在这里没有帮助,因为改变值的不是用户.

The input event is not helping here because it's not the user who is changing the value.

在 Chrome 上进行测试时,不会触发 change 事件.也许是因为元素没有失去焦点(它没有获得焦点,所以它不能失去焦点)?

When testing on Chrome, the change event isn't fired. Maybe because the element didn't lose focus (it didn't gain focus, so it can't lose it)?

推荐答案

基于@tj-crowder 和@maciej-swist 的答案,让我们添加这个,带有.apply"功能,可以在不重新定义对象的情况下防止无限循环.

Based on @t-j-crowder and @maciej-swist answers, let's add this one, with ".apply" function that prevent infinite loop without redefining the object.

 function customInputSetter(){

  var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
  var originalSet = descriptor.set;

  // define our own setter
  descriptor.set = function(val) {
    console.log("Value set", this, val);
    originalSet.apply(this,arguments);
  }

  Object.defineProperty(HTMLInputElement.prototype, "value", descriptor);
}

这篇关于JavaScript 更改输入值时的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:43