我正在做一个扩展 DOM 功能的项目,但我无法提供任何合理的例子来说明为什么 Attr
类存在,以及它可以用来做什么。
鉴于 HTML 属性始终只是字符串,例如 <input type="date" name="your-birthday" />
, 已经存在 setAttribute
和 getAttribute
Element
上的方法直接使用属性值作为字符串的原型(prototype)。
Attr
的引用对象可以通过使用attr = element.attributes[0]
获得, 然后可以使用 attr.value = "updated value";
等方法进行交互例如。
请有人能给我一个用法示例来启发我何时使用 Attr
直接类,因为它没有构造函数,而且据我所知不能传递给 DOM 中的任何方法?
引用:
-
Attr
类别:https://developer.mozilla.org/en-US/docs/Web/API/Attr -
getAttribute
: https://developer.mozilla.org/en/docs/Web/API/Element/getAttribute -
setAttribute
: https://developer.mozilla.org/en/docs/Web/API/Element/setAttribute -
hasAttribute
: https://developer.mozilla.org/en/docs/Web/API/Element/hasAttribute
最佳答案
它有用的一件事是,当 DOM 文档是 XML document 时你想知道 namespace URI或 namespace prefix的属性。
为了理解为什么这可能特别有用,我将在 Attr.namespaceURI
上引用 MDN 文档(强调我的):
Per the Namespaces in XML specification, an attribute does not inherit its namespace from the element it is attached to. If an attribute is not explicitly given a namespace, it has no namespace.
为了说明这一点,考虑这个例子,在这个例子中我们用 DOMParser
解析一个 XML 字符串。创建一个 XMLDocument
实例:
我故意给了<book>
具有不明确本地名称的两个属性 id
, 来说明它的用处。
const XML = '<?xml version="1.0" encoding="utf-8"?>\
<books xmlns:lib="http://example.com/xml/library">\
<book id="book-one" lib:id="1">\
</book>\
</books>';
var parser = new DOMParser;
var doc = parser.parseFromString( XML, 'application/xml' );
// is our Document an instance of XMLDOcument?
console.log( doc instanceof XMLDocument );
// fetch all Attr instances of the first <book> element
var attributes = doc.querySelector( 'book' ).attributes;
for( var attribute of attributes ) {
// output namespace info about the Attr instance
console.log( attribute.localName, attribute.prefix, attribute.namespaceURI, attribute.value );
}
另一个用例是如果你想移动 Attr
节点到另一个 Element
:
div2.setAttributeNode( div1.removeAttributeNode( div1.getAttributeNode( 'class' ) ) );
当然,我不认为上面的示例是常见用法的示例。这可能就是为什么 Element.getAttributeNode()
, Element.getAttributeNodeNS()
, Element.setAttributeNode()
和 Element.setAttributeNodeNS()
是marked as obsolete on MDN .
但是,w3c.org 上的 DOM 规范尚不明确(请参阅 8.2 DOM Core
部分中的警告),whatwg 上的 DOM 规范也不是
关于javascript - DOM Attr 类使用示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717498/