DOM Element对象hasAttribute()
在当在此元素上指定具有给定名称的属性或具有默认值时返回true
,否则返回false
。
语法
以下是hasAttribute()
方法的使用语法。
elementObj.hasAttributeNS(attName)
参数
attName
- 它是表示属性名称的字符串。
返回值
- 它返回一个布尔值
true
或false
。
示例
文件:node_ns.xml 的内容如下 -
<?xml version = "1.0"?>
<Company>
<Employee xmlns:e = "http://www.yiibai.com/technical/" category = "technical">
<e:FirstName e:lang = "en">Tianya</e:FirstName>
<e:LastName>Su</e:LastName>
<e:ContactNo>0898-1234567890</e:ContactNo>
<e:Email>tanmaypatil@xyz.com</e:Email>
</Employee>
<Employee xmlns:n = "http://www.yiibai.com/non-technical/" category = "non-technical">
<n:FirstName n:lang = "en">Taniya</n:FirstName>
<n:LastName>Lee</n:LastName>
<n:ContactNo>0898-1234567890</n:ContactNo>
<n:Email>tanyia@yiibai.com</n:Email>
</Employee>
</Company>
以下示例演示了hasAttribute()
方法的用法 -
<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("/node_ns.xml");
x = xmlDoc.getElementsByTagName("Employee")[0];
document.write("hasattribute的值是: "+x.hasAttribute("category"));
</script>
</body>
</html>
执行上面示例代码,得到以下结果 -