检查文档是否为根节点

7

我需要知道文档元素是否是页面的根节点。例如:

<html> <-- ROOT Node
   <head></head>
   <body>
      <iframe>
         <html>...</html> <-- other document 
      </iframe>
      <iframe>
         <html>...</html> <-- other document
      </iframe>
   </body>
</html>

在 iframe 1 或 2 中执行的 Javascript 应该知道它们的文档节点是否为根节点。

希望我能帮到您。

5个回答

14

你应该可以使用top实现这个功能:

if (window.top.document === window.document) {
    // we're in the outermost window
}

+1,但是 top.document === window.document 就足够了,window.top 只是使用 top 的一种较慢的方式。 - Martin Jespersen
@Martin 确实如此,但我更喜欢明确表达。我可以想象出一种情况,我会将变量命名为“top”。 - lonesomeday
你可以尝试,但在大多数浏览器中,如果你尝试给 top 赋值,它要么会被忽略,要么会抛出一个错误。此外,window 只是一个指向该框架全局命名空间的伪对象,所以显式地调用它只是绕了一个大弯路,有点像观光而不是使用高速公路。 - Martin Jespersen
@Martin 只有在将 top 设置为全局变量时才会出现问题。如果你在函数内使用 var top 进行设置,它就可以正常工作。 - lonesomeday
非常正确,说得好。我自己可能永远不会使用那个名称的变量(我在14年编写js代码中从未使用过一次),但其他人可能会使用,所以这是很好的建议 :) - Martin Jespersen

0
if (window == window.parent) {
   alert("I'm not in a frame");
}

0
在您的顶级文档中创建一个函数,该函数返回其根节点,然后通过使用 window.top 引用从您的 iframe 文档中调用此函数:
在您的顶级文档中:
function getRootNode()
{
 //returns the rootNode
}

在您的 iframe 文档中:
var rootNode = window.top.document.getRootNode();

0

我怀疑,鉴于一个 <iframe> 的内容是不同的文档,它们都会报告为根节点。你最好检查一下 document.parent 是否为空。


0

试试这个:

if(currentnode.parentNode == null) { alert("is root node") } 

// currentnode 是你将要选择的节点


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接