javascript – DOM Attr类使用示例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – DOM Attr类使用示例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2350字,纯文字阅读大概需要4分钟。
内容图文
![javascript – DOM Attr类使用示例](/upload/InfoBanner/zyjiaocheng/781/226687406c864393a236699ef3622d08.jpg)
我正在开发一个扩展DOM功能的项目,我无法提供任何合理的示例,说明为什么Attr类存在,以及它可以用于什么.
鉴于HTML属性始终只是字符串,例如< input type =“date”name =“your-birthday”/>,Element原型上已存在setAttribute和getAttribute方法,它们直接使用Attribute的值作为串.
可以使用attr = element.attributes [0]获取Attr对象的引用,然后可以使用诸如attr.value =“updated value”之类的方法进行交互.例如.
如果我没有使用构造函数,并且据我所知不能传递给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 07003 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节点移动到另一个元素:
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核心中的警告),whatwg上的DOM规范也没有
内容总结
以上是互联网集市为您收集整理的javascript – DOM Attr类使用示例全部内容,希望文章能够帮你解决javascript – DOM Attr类使用示例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。