获取 0 的文档元素返回什么

what does getting the documentElement of 0 return

本文关键字:返回 什么 元素 文档 获取      更新时间:2023-09-26

大多数JavaScript库都包含类似于以下内容的行:

    var b = (a ? a.ownerDocument || a: 0).documentElement;

如果a null(0).documentElement应该返回什么?

来自 jQuery/Sizzle 评论:

http://jsapi.info/jquery/1.7.2/jQuery.isXMLDoc

在尚不存在的情况下验证 documentElement (例如在IE中加载iframe-#4833)

所以这只是返回undefined的可爱语法 - 这是在0上调用documentElement的结果。

下一行有检查:

return documentElement ? documentElement.nodeName !== "HTML" : false;

所以它无论如何都会返回 false。

很可能

:未定义还有什么?

它是以下的简写:

var b; // defaults to "undefined"
if (a) b = a.ownerDocument.documentElement || a.documentElement;

它正在检查 DOM 文档元素是否已在 DOM 树中创建。(0).documentElement 访问默认为 undefined 的不存在的属性。如果"documentElement"未定义,则尚未创建。

这可能更容易可视化:

a.ownerDocument.documentElement || // try this first
a.documentElement || // fallback
undefined; //documentElement has not been created yet

它不仅仅是另一个答案所建议的"可爱的语法"。这是"手动缩小",因为在像 JavaScript 这样的动态类型语言中,缩小器无法确定"a"和"a.ownerDocument"可能属于同一类型,因此只会删除空格。

通过闭包编译器运行我的上述代码会产生:

var b;a&&(b=a.documentElement||a.ownerDocument.documentElement);

同时,您在问题中提出的"手动缩小"版本通过缩小器运行会产生:

var b=(a?a.ownerDocument||a:0).documentElement;

结果:

Without manual minification (my code) + Closure minifier: 64 characters
With manual minification (your original code): 54 characters
With manual minification (your original code) + Closure minifier: 47 characters

ownerDocument 属性返回 html 节点的文档所有者,作为文档对象。HTML 文档本身是元素的所有者文档。如果它是空的,我猜 (0).documentElement 在页面包含多个文档时返回初始文档。所有者文档可用于在同一页面的多个文档中相应地创建HTML文档