以编程方式更改输入时,on change 的解决方案不起作用 [英] Solution for on change doesn't work when input is changed programmatically

查看:42
本文介绍了以编程方式更改输入时,on change 的解决方案不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了为什么 onchange 不起作用? 现在我知道了,

I have already read Why onchange doesn't work? and now I know that,

onchange 事件仅在用户更改输入.如果输入更改,则不应触发以编程方式.

The onchange event only fires if the user changes the value of the input. It isn't supposed to fire if the input is changed programmatically.

但是我有一个输入字段,当用户通过网站内的 Google 地图小部件更改位置时,该字段会自动填充.当它发生时,我想获得自动填充的值并填充另一个输入字段.当以编程方式更改输入时,如何检测或触发函数?

But I have an input field which is automatically filled when user change a location by Google map widget inside a website. When it happens, I want to get that automatically filled value and fill another input filed. How can I detect or fire function when input is changed programmatically?

推荐答案

您可以通过覆盖输入的 value 属性的 setter 函数来实现这一点.因此,每次有人以编程方式设置 value 时,您的覆盖设置器都会被触发:

You could achieve this by overriding the setter function of the input's value property. So every time anyone sets the value programmatically your overriden setter will be triggered:

const input = document.getElementById('input');

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');

Object.defineProperty(input, 'value', {
    set: function(t) {
        console.log('Input value was changed programmatically');
        return descriptor.set.apply(this, arguments);
    },
    get: function() {
      return descriptor.get.apply(this);
    }
});

function changeInput() {
  input.value += '1';
}

<input id="input">
<button onclick="changeInput()">Change</button>

这篇关于以编程方式更改输入时,on change 的解决方案不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆