gpt4 book ai didi

javascript - HTML 中的命名空间是什么?

转载 作者:行者123 更新时间:2023-12-02 02:22:01 26 4
gpt4 key购买 nike

我试图理解 HTML 中的命名空间,这非常简单。

使用这两个命令有什么区别。为什么应该使用 createElementNS 而不是 createElement

const a = document.createElementNS("http://www.w3.org/2000/svg", "svg")
const b = document.createElement("svg")

资源:

最佳答案

命名空间使不同类型的 XML 可以拥有具有不同含义的相同标记。这是 Namespaces crash course on MDN 的摘录:

It has been a long standing goal of the W3C to make it possible for different types of XML based content to be mixed together in the same XML file. For example, SVG and MathML might be incorporated directly into an XHTML based scientific document. Being able to mix content types like this has many advantages, but it also required a very real problem to be solved.

Naturally, each XML dialect defines the meaning of the markup element names described in its specification. The problem with mixing content from different XML dialects in a single XML document is that the elements defined by one dialect may have the same name as elements defined by another. For example, both XHTML and SVG have a element. How should the user agent distinguish between the two? In fact how does the user agent tell when XML content is something it knows about, and not just a meaningless XML file containing arbitrary element names unknown to it?

在您的具体示例中,不同之处在于 createElement("svg") 创建一个带有标签名称 svgHTML 元素(其中不存在,没有具有该标记名称的 HTML 元素)。但是 createElementNS("http://www.w3.org/2000/svg", "svg") 创建一个带有标签名称 svg< 的 SVG 元素 (确实存在)。

这很重要,因为 SVG 元素已经定义了行为和各种方法,等等您可能想要的。尝试将其创建为 HTML 元素,您不会获得这些行为和方法:

const a = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const b = document.createElement("svg");

console.log("a instanceof SVGSVGElement?", a instanceof SVGSVGElement); // a instanceof SVGSVGElement? true
console.log("b instanceof SVGSVGElement?", b instanceof SVGSVGElement); // b instanceof SVGSVGElement? false

console.log("typeof a.currentScale:", typeof a.currentScale); // typeof a.currentScale: number
console.log("typeof b.currentScale:", typeof b.currentScale); // typeof b.currentScale: undefined


¹ HTML 不是 XML,但有时确实嵌入了 XML(例如:SVG)。 (有 XHTML,它是 XML,但请注意 XHTML 不是 HTML。)

关于javascript - HTML 中的命名空间是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66278014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com