Difference between setAttribute and setAttributeNS(null,

Difference between setAttribute and setAttributeNS(null,

本文关键字:null setAttributeNS and between setAttribute Difference      更新时间:2023-09-26

调用 setAttribute 和 setAttributeNS 以 null 作为命名空间参数有什么区别?

另外,使用getAttribute()然后设置AttributeNS是否有问题?

setAttribute() 是一个 DOM 1 函数。setAttributeNS() 是一个 DOM 2 函数,它通过指定应应用于第一个参数中的标记/属性的 xmlns 命名空间来解决标记或属性名称冲突的问题。

如果属性没有定义的命名空间前缀,则第一个参数必须为 null。你可以使用 setAttribute(),但为了保持一致性,建议坚持使用 setAttributeNS()。看:

https://developer.mozilla.org/en/docs/Web/SVG/Namespaces_Crash_Course#Scripting_in_namespaced_XML

"但是,请仔细注意:XML 1.1 中的命名空间建议 声明不带前缀的属性的命名空间名称 没有值。换句话说,虽然属性属于 标签的命名空间,不要使用标签的命名空间名称。 相反,您必须使用 null 作为非限定的命名空间名称 (无前缀)属性。

setAttributeNS 方法是一个 XML 方法,不适用于 HTML 元素。

以下是来自 MDN 文档的英文解释:

// Given:
//   <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace"
//     special:specialAlign="utterleft" width="200px" /> 
d = document.getElementById("div1"); 
d.removeAttributeNS("http://www.mozilla.org/ns/specialspace", "specialAlign"); 
// Now:
//   <div id="div1" width="200px" />
因此,由此

看来,xmlns:special="http://www.mozilla.org/ns/specialspace"是命名空间special的声明,然后用于上下文化special:specialAlign

setAttributeNS 用于指定命名空间并添加具有命名空间的新属性。 NS代表这一点。它还需要三个参数

element.setAttributeNS(ns,name,value)
ns  :namespace URI of the attribute to set
name:Name of the attribute to set
value:Value of the attribute to set
setAttribute(name,value) which is use to add a new attribute or change the value of existing attribute.