这个
.value
属性
只有脚本编写器调用
setAttribute('value'
设置新值,这是一件很奇怪的事情。在几乎所有情况下,我都希望通过将
value
直接属性,例如:
input.value = 'foo';
打电话
setAttribute
确实会显示被检查的DOM的变化
属性
,例如:
<input value="somevalue">
const input = document.querySelector('input');
input.setAttribute('value', 'foo');
console.log(input.outerHTML);
<input>
但只是分配给
.价值
财产
元素的值不会导致这样的更改:
const input = document.querySelector('input');
input.value = 'foo';
console.log(input.outerHTML);
<输入>
分配给
.价值
实际上调用
setter函数
在
HTMLInputElement.prototype
:
console.log(HTMLInputElement.prototype.hasOwnProperty('value'));
你可以
阴影
通过放置getter/setter
价值
直接在元素本身上,setter调用您自己的函数,允许您监听更改:
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';
<输入>