setAttribute()不像我期望的那样工作 [英] setAttribute() doesn't work the way I expect it to
问题描述
这行代码:
document.getElementById('01').getElementsByTagName("input")[0].setAttribute("value", "1");
当输入还没有值时,效果非常好。但是当输入已经有值时,它不会改变该值。这是为什么?
works perfectly fine when "input" doesn't already have a value. but when the input already has a value, it wouldn't change the value. why is that?
推荐答案
听起来你在元素属性 value
之间遇到了令人困惑的区别 value
属性。这些不是相同的事物。
Sounds like you faced a confusing difference between element property value
and value
attribute. Those are not the same things.
事情是value-attribute用于默认值的目的,所以如果元素已经有属性值然后更改value-attribute将不会反映在UI中。
The thing is that value-attribute serves the purpose of the default value, so if the element already has a property value then changing value-attribute will not be reflected in UI.
文档说 this :
使用setAttribute()修改某些属性,最值得注意的是XUL中的值,工作不一致,因为属性指定了默认值。要访问或修改当前值,您应该使用属性。例如,使用elt.value而不是elt.setAttribute('value',val)。
Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val).
所以为了证明这种情况,请考虑这个小演示:
So to demonstrate this situation consider this little demo:
document.getElementById("01").getElementsByTagName("input")[0].value = 'property set';
document.getElementById("01").getElementsByTagName("input")[0].setAttribute("value", "two");
<div id="01">
<input type="text" />
</div>
在上面的代码段中,value属性确实已更新为值 two
,如果您尝试使用 getAttribute读取它,则可以对其进行验证( 'value')
,但value-property优先于属性,因此以后不会呈现。
In the above snippet the value attribute is indeed updated to value two
and you can verify it if you try to read it back with getAttribute('value')
, however the value-property takes precedence over attribute, so later is not rendered.
这篇关于setAttribute()不像我期望的那样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!