以编程方式更改输入时,on change 的解决方案不起作用

编程入门 行业动态 更新时间:2024-10-26 04:25:32
本文介绍了以编程方式更改输入时,on change 的解决方案不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我已经阅读了为什么 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-23 08:40:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1039149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   解决方案   方式   change

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!