提问人: 提问时间:12/20/2016 最后编辑:BoltClock 更新时间:12/20/2016 访问量:780
带前缀和不带前缀的createElementNS有什么区别?
What is the difference between createElementNS with a prefix and without it?
问:
在链接到 XHTML 页面的 JS 中,我使用 创建新元素,如下所示:createElementNS
const NS = 'http://my.site/xmlns';
const el1 = document.createElementNS(NS, 'custom');
const el2 = document.createElementNS(NS, 'p:custom');
我无法理解在第二个参数中使用命名空间前缀创建的元素与没有它创建的元素之间有什么区别。例如,这些 CSS 规则对这两个元素具有相同的效果:
@namespace p url('http://my.site/xmlns');
p|custom { background: yellow; }
接下来,调用 of 返回包含两个元素的 a,而返回一个空的 ,这对我来说似乎很奇怪。document.getElementsByTagNameNS(NS, 'custom')
HtmlCollection
document.getElementsByTagNameNS(NS, 'p:custom')
HtmlCollection
那么,创建带有命名空间前缀的元素和没有命名空间前缀的元素有什么区别呢?
答:
document.createElementNS()
要求第二个参数是限定的标记名称。 是一个限定的标签名称,所以更正确;我怀疑之所以有效是由于遗留原因。p:custom
document.createElementNS(NS, 'p:custom')
document.createElementNS(NS, 'custom')
另一方面,document.getElementsByTagNameNS()
期望第二个参数是本地标签名称。 是本地标记名称。(如果没有命名空间,则它也是其限定的名称。custom
custom
由于元素是命名空间的,并且它们的限定名称是 ,因此它们的本地名称是 ,因此不返回任何内容,因为不是它们的本地名称。p:custom
custom
document.getElementsByTagNameNS(NS, 'p:custom')
p:custom
评论
createElementNS()
评论