关于attributes的使用
attributes用来检索属于该对象的属性的集合,它也是一个伪数组(可参考上篇文章:将HTMLCollection/NodeList/伪数组转换成数组),什么情况下会用到这个对象呢?比如有下面的一段html代码:
<div id=”content”></div>
<div id=”test” width=”400” userid=”1234” username=”abcd” >测试</div>
如果要取里面的自定义的属性集合应该怎样取呢?因为自定义的属性名称可能会有变化,也就是说具有不定性,此时再单独用getAttribute就不好用了。
而attributes对象即可解决此问题,
<script>
var oElem = document.getElementById(“test”);
var oCons = document.getElementById(“content”);
oCons.innerHTML = ‘’;
var oAttribs = oElem.attributes;
for (var i = 0; i < oAttribs.length; i++)
{
var oAttrib = oAttribs[i];
oCons.innerHTML += oAttrib.nodeName + ‘=’ +
oAttrib.nodeValue <BR>’;
}
</script>
此时你在Firefox下可以看到以下输出的内容:
username=abcd
userid=1234
width=400
id=test
但是换个浏览器,比如IE8,却发现输出的内容远远多于此:
……
onended=null
onemptied=null
aria-describedby=
onmouseenter=null
onbeforecut=null
aria-activedescendant=
aria-multiselectable=
onprogress=null
align=
nofocusrect=null
noWrap=false
username=abcd
userid=1234
width=400
它输出了许多你所不需要的属性和值,因为我们目前只关心我们自定义的那些属性和值,如何达到目的呢?msdn给出了方案:http://msdn.microsoft.com/en-au/library/ms534637(v=vs.85).aspx.aspx)
specified属性:这个属性是一个只读属性,没有默认值,它有两种值:
true: 说明这个属性是明确指定的。
false: 说明这个属性未指定。
官网对specified的Remark:
Gets a value that indicates whether an attribute is explicitly given a value.
An attribute value is specified if it is assigned through HTML or script.
New for Windows Internet Explorer 9 Internet Explorer 9. When webpages are displayed in IE9 Standards mode, the attributes collection does not contain attributes that are not specifically created (unlike previous Internet Explorer versions). As a result, the specified property returns true for every item in the attributes collection.
我们可以理解为当这个值为true时,这个属性就是你额外增加即自定义的属性。按照这个说法,我们把上面的代码稍微改下:<script>
var oElem = document.getElementById(“test”);
var oCons = document.getElementById(“content”);
oCons.innerHTML = ‘’;
var oAttribs = oElem.attributes;
for (var i = 0; i < oAttribs.length; i++)
{
var oAttrib = oAttribs[i];
oCons.innerHTML += oAttrib.nodeName + ‘=’ +
oAttrib.nodeValue + ‘ (‘ + oAttrib.specified + ‘)<BR>’;
}
</script>
结果:FF:
username=abcd (true)
userid=1234 (true)
width=400 (true)
id=test (true)
IE8:
……
onbeforecut=null (false)
aria-activedescendant=
(false)
aria-multiselectable= (false)
onprogress=null (false)
align=
(false)
nofocusrect=null (false)
noWrap=false (false)
username=abcd
(true)
userid=1234 (true)
width=400 (true)
可以看到你自定义的属性后面的specified值是为true的,而其他原生的为false,这样我们就可以得到我们预期的属性及值了。
<script>
var oElem = document.getElementById(“test”);
var oCons = document.getElementById(“content”);
oCons.innerHTML = ‘’;
var oAttribs = oElem.attributes;
for (var i = 0; i < oAttribs.length; i++){
var oAttrib = oAttribs[i];
if(oAttrib.specified) {
oCons.innerHTML += oAttrib.nodeName + ‘=’ +
oAttrib.nodeValue + ‘ (‘ + oAttrib.specified + ‘)<BR>’;
}
}
</script>
IE8:
id=test (true)
username=abcd (true)
userid=1234 (true)
width=400 (true)
至此,你对自定义属性集合的获取已经完成,目前测试过的需要增加specified判断的浏览器为IE6-8。