08月 11th, 2009

INPUT中attribute和property的差异

javascript, by vangie.

今天在firefox下遇到一个奇怪的问题。

html中有下面一个INPUT元素

[html]<input id="q" name="q" value="123"/>[/html]

使用input.getAttribute可以取得该input的值

[javascript]document.getElementById("q").getAttribute("value"); //return 123[/javascript]

但是当通过界面输入将INPUT的值改为456之后,在通过input.getAttribute的方式取值,仍然返回123,但是使用input.value可以返回456.

[javascript]document.getElementById("q").getAttribute("value"); // return 123
document.getElementById("q").value; //return 456[/javascript]

下面的网页中有对该问题的完整的分析和测试(已被墙,请用代理访问)

http://updatepanel.net/2008/12/31/more-on-getattribute-setattribute-and-the-value-attribute/

参考上面的分析可以还原出firefox下的实现

假设

  • “value” property is element.value;
  • “value” attribute is element.getAttribute(”value”);
  • HtmlElement中存在_properties[]和_attributes[]两个关联数组来存放propertie和attribute属性

那么在firefox中

htmlElement.value作为等式右值时等价于

[javascript]function(){
return this._properties["value"]||this._attributes["value"]
}[/javascript]

htmlElement.value作为等式左值时等价于

[javascript]function(right_value){
this._properties["value"]=right_value;
}[/javascript]

htmlElement.getAttribute(“value”)等价于

[javascript]function(){
return this._attributes["value"];
}[/javascript]

htmlElement.setAttribute(“value”,”123″)等价于

[javascript]function(name,value){
this._attributes[name]=value;
}[/javascript]

而在IE中property和attribute的值是完全等价的不存在差异。

Last 5 posts by vangie

Back Top

Responses to “INPUT中attribute和property的差异”

  1. 没有任何评论。
  1. 没有任何引用。

发表回复

Back Top