您如何监听/检测输入值的更改 - 当输入值通过 javascript 更改时? [英] How do you listen / detect changes to an input value - when the input value is changed via javascript?

查看:26
本文介绍了您如何监听/检测输入值的更改 - 当输入值通过 javascript 更改时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 inputgoogle autoComplete 连接.

I've got an input with google autoComplete connected.

当用户在 seachResults 中上下移动时,输入的值会通过 JavaScript 动态改变.

When the user moves up and down through the seachResultsthe value of the input is changed dynamically via JavaScript.

我想在任何给定时间捕获输入中的值.

I'd like to capture the value that is in the input at any given time.

我已经尝试了 onChangeonInput 但由于没有触发事件,并且 DOM 节点的 value 未设置 - 没有更新.

I've tried onChange and onInput but since no event is getting fired, and the value of the DOM Node is not getting set - there are no updates.

您如何检测通过 JavaScript 动态更新的 input 更改?

推荐答案

.value attribute 只会在脚本编写者调用了 setAttribute('value' 来设置新值,这是一件很奇怪的事情.在几乎所有情况下,我希望通过直接分配给 value 属性来设置值,例如:

The .value attribute will only change if the script-writer has called setAttribute('value' to set the new value, which is quite an odd thing to do. In almost all situations, I would expect the value to be set by assigning to the value property directly, eg:

input.value = 'foo';

调用 setAttribute 确实会显示被检查的 DOM attribute 的变化,例如:

Calling setAttribute will indeed show a change in the inspected DOM attribute, eg:

<input value="somevalue">

const input = document.querySelector('input');
input.setAttribute('value', 'foo');
console.log(input.outerHTML);

<input>

但是仅仅分配给元素的 .value property 不会导致这样的变化:

But just assigning to the .value property of the element will not result in such a change:

const input = document.querySelector('input');
input.value = 'foo';
console.log(input.outerHTML);

<input>

分配给 .value 实际上会调用 HTMLInputElement.prototype 上的 setter 函数:

Assigning to the .value actually invokes a setter function on HTMLInputElement.prototype:

console.log(HTMLInputElement.prototype.hasOwnProperty('value'));

您可以通过将 value 的 getter/setter 直接放在元素本身上来隐藏这一点,使用 setter 调用您自己的函数,允许您侦听更改:

You can shadow this by putting a getter/setter for value directly on the element itself, with the setter invoking your own function, allowing you to listen for changes:

const { get, set } = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
const input = document.querySelector('input');
Object.defineProperty(input, 'value', {
  get() {
    return get.call(this);
  },
  set(newVal) {
    console.log('New value assigned to input: ' + newVal);
    return set.call(this, newVal);
  }
});


// example of autocomplete trying to change the input value:
input.value = 'foo';

<input>

这篇关于您如何监听/检测输入值的更改 - 当输入值通过 javascript 更改时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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