怎么给网站添加图标,企业网站建设哪家最好,购物网站页面,wordpress win2008 r2在DOM#xff08;Document Object Model#xff09;中#xff0c;attributes 是一个 NamedNodeMap 对象#xff0c;它包含了元素的所有属性。然而#xff0c;attributes 集合中的每个属性本身是一个 Attr 对象#xff0c;而不是简单的字符串或值。Attr 对象有几个属性Document Object Model中attributes 是一个 NamedNodeMap 对象它包含了元素的所有属性。然而attributes 集合中的每个属性本身是一个 Attr 对象而不是简单的字符串或值。Attr 对象有几个属性其中 nodeName 和 nodeValue 是两个常用的。
attributes.nodeName
nodeName 属性返回属性的名称。对于属性节点它总是返回属性的名称。
attributes.nodeValue
nodeValue 属性返回或设置属性的值。对于属性节点它返回或设置属性的值。但需要注意的是并非所有属性都有值比如一些HTML5的布尔属性如 disabled 或 required它们在HTML中只存在而不带值例如 input disabled但在DOM中这些属性可能会有一个空字符串作为值。
代码举例
假设我们有以下的HTML元素 html复制代码
input typetext idmyInput valueHello, World! disabled
在JavaScript中我们可以访问该元素的属性并检查它们的 nodeName 和 nodeValue javascript复制代码
var inputElement document.getElementById(myInput); // 访问 type 属性 var typeAttr inputElement.attributes.getNamedItem(type); console.log(typeAttr.nodeName); // 输出: type console.log(typeAttr.nodeValue); // 输出: text // 访问 value 属性 var valueAttr inputElement.attributes.getNamedItem(value); console.log(valueAttr.nodeName); // 输出: value console.log(valueAttr.nodeValue); // 输出: Hello, World! // 访问 disabled 属性注意虽然HTML中没有值但DOM中可能有 var disabledAttr inputElement.attributes.getNamedItem(disabled); console.log(disabledAttr.nodeName); // 输出: disabled // 对于布尔属性nodeValue可能是一个空字符串但属性本身存在即表示该属性被设置了 console.log(disabledAttr.nodeValue); // 在某些浏览器中可能输出空字符串 但在其他浏览器中可能不输出或输出undefined // 注意对于布尔属性通常检查属性对象本身是否存在就足够了 if (disabledAttr) { console.log(Input is disabled.); // 输出: Input is disabled. }
在这个例子中你可以看到 nodeName 总是返回属性的名称而 nodeValue 返回属性的值如果有的话。对于布尔属性如 disablednodeValue 可能不是很有用因为它们的存在本身就表示了它们的值即它们被设置了。