Attribute与Property关系

总的来说,其实是HTML Attribute 与 DOM property之间的关系。

1 什么是Property?

JS DOM Object对象有property。一个property可能是不同数据类型的(boolean,string,etc.),而且这些property普遍都是标准的(即可以通过'.'操作符直接引用property的值)。

1 <a href='page2.html' class='link classes' name='linkName' id='linkID'>Hi</a> // obj.href obj.className obj.name obj.id etc.

2 什么是Attribute?

Attribute只是针对HTML本身(即HTML标签内直接写着的),一个attribute只有String一种数据类型。

1 <input type="checkbox" checked=true/>
2 $('input').prop('checked'); // property -> returns true
3 $('input').attr('checked');  // attribute -> returns "checked"

3 不同点

a 如果一个元素有一个默认value,attribute总是显示Html本身上的值,即使property已经对value做出了改变。

1 <input type="text" name="username" value="user123">
2 $('input').prop('value', '456user'); //改变property值
3 $('input').prop('value'); // returns "456user"
4 $('input').attr('value');  // returns "user123"

b HTML元素标签内定义属性对Attribute和Property影响。

标准属性概念是对于DOM Object存在的,比如id,className,dir,etc.
定义标准属性,同时影响attribute和property
定义非标准属性,只在attribute中存在,而不在property
1
<input type="text" custom="something"> 2 $('input').attr('custom'); // returns "something" 3 $('input').prop('custom'); // returns undefined

c 代码更改属性对Attribute和Property影响。

 // 添加标准属性,同时影响attribute和property
1
<div id="test" class="button"></div> 2 var div = document.getElementById('test'); 3 div.className = 'red-input'; 4 div.getAttribute('class'); // return string: "red-input" 5 div.setAttribute('class','green-input'); 6 div.className; // return string: "green-input" // 添加非标准属性,互相不影响
7
div.jjj = 123; 8 div.getAttribute('jjj'); // return null 9 div.setAttribute('lll', 123); 10 div.lll; // return undefined;
posted @ 2016-10-27 14:47  5Mi17  阅读(254)  评论(0编辑  收藏  举报