-
HTML属性和DOM属性的对应关系
每个HTML元素的属性都有对应的DOM对象属性
<div>
<label for="userName">用户名:</label>
<input id="userName" type="text" class="u-txt"/>
</div>input.id; //"userName" input.type; //"text" input.className; //"u-txt" label.htmlFor; //"userName"
2.属性操作的方式
-
property accessor(属性访问器)
-
读取元素属性
input.className; //"u-txt"
input["id"]; //等价于input.id,"userName" -
写入元素属性
input.value = "www.baidu.com"; //在input元素节点增加value属性,设置它的值为"www.baidu.com" -
获取元素的类型,转换过的实用对象
<input class="u-txt" maxlength="10" disabled onclick="showSuggest();" />input.className; //"u-txt", String input.maxlength; //10, Number input.disabled; //true, Boolean input.onclick; //Function
-
特点
通用性差,名字异常;扩展性差;优势是获取的元素类型为实用对象
-
-
getAttribute/setAttribute
-
读取属性,
var attr = element.getAttrubute(attrubuteName);
<div>
<label for="userName">用户名:</label>
<input id="userName" type="text" class="u-txt"/>
</div>input.getAttribute("class"); //u-txt
-
写入属性,
element.setAttribute(name, value);
<div>
<label for="userName">用户名:</label>
<input id="userName" type="text" class="u-txt"/>
</div>input.setAttribute("value", "www.baidu.com"); input.setAttribute("disabled", "");
-
获取元素的类型,属性字符串
<input class="u-txt" maxlength="10" disabled onclick="showSuggest();" />input.getAttribute("class"); //"u-txt", String input.getAttribute("maxlength"); //"10", String input.getAttribute("disabled"); //"", String input.getAttribute("onclick"); //"showSuggest()", String
-
特点
获取属性值为字符串,通用性强
-
-
dataset(自定义属性)
-
定义
- 形式为
HTMLElement.dataset
,即HTML
上Element
元素自定义的属性 - 名称为
data-*
,即data-
开头加名称 - 用于元素上用户自定义的数据保存
- 数据通常使用 AJAX 获取并存储在节点之上
- 形式为
-
示例
<div id='user' data-id='123456' data-accountName='nc' data-email='mail@gmail.com'></div>div.dataset.id; //'123456' div.accountName; //'nc' div.dataset.email; //'mail@gmail.com'
-
思考题:
dataset
在低版本 IE 不可使用,如何通过getAttribute
与setAttribute
来做兼容。
-
网友评论