RSS
 

Posts Tagged ‘javascript’

INPUT中attribute和property的差异

11 Aug

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

html中有下面一个INPUT元素

<input id="q" name="q" value="123"/>

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

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

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

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

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

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作为等式右值时等价于

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

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

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

htmlElement.getAttribute(“value”)等价于

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

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

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

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