问题描述
我有输入
,其中 google autoComplete
已连接。
当用户在 seachResults
中上下移动时,输入的值会通过JavaScript动态更改。
When the user moves up and down through the seachResults
the 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.
我试过 onChange
和 onInput
但是从那以后没有事件被触发,并且 DOM节点
的值
未设置 - 没有更新。
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
How do you detect changes to the input
that are dynamically updated via JavaScript
?
推荐答案
.value
attribute 只有在脚本编写者调用 setAttribute('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 属性中显示更改,例如:
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
属性不会导致这样的更改:
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'));
您可以通过直接在元素本身上使用getter / setter value
来设置 shadow 调用您自己的函数,允许您监听更改:
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更改输入值时,你如何监听/检测输入值的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!