您的位置:首页 > 运维架构

DOM中Property与Attribute的区别

2015-12-31 18:10 555 查看
property和attribute的汉语翻译几乎相同,都有“属性”的意义(这里姑且称attribute为“特性”,以方便区分),而他们的取值也经常相同,但有时又会踩坑,发现二者会不相等,不同步。

0.奇葩的IE
本文开始之前不得不提一下 万恶之源IE ,在IE<9中,浏览器会把所有的property和attribute强制映射,即property = attribute. (class特殊:className = class)。正因为IE<9中的这种映射误导了很多人以为二者完全相同。

1. Property
每个DOM节点都是一个object对象,它可以像其他的js Object一样具有自己的property和method,所以 property的值可以是任何数据类型,大小写敏感,原则上property应该仅供js操作 ,不会出现在html中(默认属性除外:id/src/href/className/dir/title/lang等),和其他js object一样,自定义的property也会出现在object的for...in遍历中。
eg.
var list=[];  for(var key in document.body) {    list.push(key)
}
console.log(list.join('\n'));


2. Attribute
attribute出现在dom中,js提供了getAttribute/setAttribute等方法来获取和改变它的值, attribute的值只能是字符串且大小写不敏感,最后作用于html中,可以影响innerHTML获取的值 。可以通过访问dom节点的attributes属性来获取改节点的所有的attribute。(在IE<9中,attribute获取和改变的实际上是property。)

3.自定义的Property与Attribute不同步,不相等
  html: <input type='text' id='test' value />
js:
var test = document.getElementById('test');
test.self = 'selfProperty';
console.log(test.self) =>  'selfProperty'
test.getAttribute('self') => null
conclusion:自定义的property与自定义的attribute无同步关系


4.非自定义的DOM property与 attributes 是有条件同步的
非自定义的属性(id/src/href/name/value等),通过setAttribute修改其特性值可以同步作用到property上,而通过.property修改属性值有的(value)时候不会同步到attribute上,即不会反应到html上(除以下几种情况,非自定义属性在二者之间是同步的)。

非自定义属性(id/src/href/name/value等)未显式定义在dom中才会时,初始的property与attribute不同

html:  <input type='text' id=“testvalue” />
初始值property:  testvalue.value => “"
初始值attribute: testvalue.getAttribute('value’) => null


input:value/checked的单向同步关系
通过setAttribute改变input的value/checked都会同步到property中,但是,一旦改变他们的property值,就打破同步机制
html:  <input type='text' id=“testvalue” value='sync' />
property:  testvalue.value => 'sync'
attribute: testvalue.getAttribute('value’) => 'sync'
testvalue.setAttribute('value','abc') => 'abc'
则属性会同步: testvalue.value => 'abc'
testvalue.value = 'ddd';
则同步机制失效: testvalue.getAttribute('value’) => 'abc'


同步不是复制,同步机制依旧,值不同(src/href)
通过getAttribute获取的是href/src的实际值,而点号(property)获取的是完整的url。
html: a(id="testHr" href="/test/")
property:  testHr.href="/blog/" => 'http://f2e.souche.com/blog/'
attribute: testHr.getAttribute('href’) => '/blog/'


非直接映射的同步,虽然同步了,但是同步后的属性名字不同,或者取值方式不同:class/data-XX/style
class映射成className
data-XXX映射到 dataset.XXX,通过JQuery的attr,prop访问时候不同步。
style属性不接受字符串型赋值,只能通过style.XXX
html: <input type='text' class="abc" data-id="123" id=“testvalue” value='sync' />
testvalue.getAttribute('class') <=>testvalue.className
testvalue.setAttribute('style','color:red') <=> testvalue.style.color
testvalue.getAttribute('data-id')<=> testvalue.dataset.id


小结
property与attribute都是dom的核心功能,鉴于有的属性上会出现单项同步的情况似乎attribute貌似更保险一点,以下是二者的关系表:



(本文完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: