前端中的 Attribute & Property

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

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

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

两种主流观点:

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

HTML attribute & DOM property 关系与区别

引用Angular文档中的一段话去概括两者的关系和区别:

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。

普遍原则

  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也发生了改变。完全不讲道理 - -

<input type="text" value="123" id="myInput">

更改HTML attribute

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。

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12058655.html