前端中的 Attribute & Property

为了在翻译上显示出区别,Attribute通常被翻译为特性,Property被译为属性。
在使用上面,Angular已经代表态度javascript

Template binding works with properties and events, not attributes.
模板绑定是经过 property 和事件来工做的,而不是 attribute。

jQuery中的prop()attr()如何选择,众说纷纭... php

两种主流观点:html

  1. 对于一些公认的attribute和property,使用setAttribute(),理由是property会出现class映射过去为className,名称不统一的问题。
  2. 红宝书做者推荐操做DOM property,由于在浏览器上面表现的比较一致。

HTML attribute & DOM property 关系与区别

引用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

  1. HTML attribute 初始化 DOM property,而后它们的任务就完成了。
  2. 更改 attribute 的值,至关于再次初始化DOM property 。
  3. 更改 property 的值,property值改变,attribute值不变。

几个有表明性的映射表浏览器

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
  • 其余状况下,操做DOM与页面交互,通常状况下用prop()
  • 总的来讲,尽可能操做DOM property,只有在没有DOM property(自定义attribute或者没有相关映射),才去操做HTML attribute。
相关文章
相关标签/搜索