为了在翻译上显示出区别,Attribute通常被翻译为特性,Property被译为属性。
在使用上面,Angular已经代表态度javascript
Template binding works with properties and events, not attributes.
模板绑定是经过 property 和事件来工做的,而不是 attribute。
jQuery中的prop()
和attr()
如何选择,众说纷纭... php
两种主流观点:html
setAttribute()
,理由是property会出现class映射过去为className,名称不统一的问题。引用Angular文档中的一段话去归纳二者的关系和区别:java
HTML attribute 与 DOM property 的对比
attribute 是由 HTML 定义的。property 是由 DOM (Document Object Model) 定义的。
少许 HTML attribute 和 property 之间有着 1:1 的映射,如id。
有些 HTML attribute 没有对应的 property,如colspan。
有些 DOM property 没有对应的 attribute,如textContent。
广泛原则:chrome
几个有表明性的映射表浏览器
HTML attribute | DOM property |
---|---|
id | id |
class | className |
checked = 'checked' | checked 值为true |
为何说是广泛原则呢?在低版本的ie中,操做DOM property中的value,attribute中的value也发生了改变。彻底不讲道理 - -post
<input type="text" value="123" id="myInput">
更改HTML attributespa
myInput.setAttribute('value', 'test Attr');
浏览器 | myInput.getAttribute('value') | myInput.value |
---|---|---|
chrome ie11 ff | test Attr | test Attr |
ie8 | test Attr | test Attr |
更改DOM property翻译
document.getElementById('myInput').value = 'test property';
浏览器 | myInput.getAttribute('value') | myInput.value |
---|---|---|
chrome ie11 ff | 123 | test property |
ie8 | test property (广泛原则下应该为123) | test property |
prop()
和attr()
的选择prop()
采用的是更改DOM property的方式,基本上对应更改DOM属性。原生DOM | jQuery | 操做 |
---|---|---|
element.value | $element.prop( name[,value]) | 读写 |
delete element.propertyName | $element.removeProp( propertyName ) | 删除 |
attr()
采用的是更改HTML attribute的方式,基本上对应DOM中提供的三个操做attribute的方法。原生DOM | jQuery | 操做 |
---|---|---|
element.getAttribute(name) | $element.attr(name) | 读 |
element.setAttribute(name,value) | $element.attr(name ,value) | 写 |
delete element.removeAttribute(name) | $element.removeAttr( name ) | 删除 |
attr()
(data-*
等除外)。<form action="test.php" user-my-name="nilinli" method="post"></form>
$('form').attr('user-my-name'); // nilinli $('form').attr('action'); // test.php
prop()