19

在页面启动期间,我试图向 DOM 添加一个元素。

我有以下代码:

$(document).ready(function () {
    $(document).prepend("<div id=new_div style=z-index:1;></div>");
});

我已经在 FF21、Chrome27 和 IE10 上对此进行了测试。它们都返回标题中提到的错误(确切的措辞来自 Chrome 调试器)。

在 jquery-1.10.0.js 上调试,我将问题追踪到第 5998 行

safeFrag = document.createDocumentFragment()

显然文档为空。沿着堆栈跟踪向上到domManip第 6249 行,对象被传递为this[ 0 ].ownerDocument,它为空。

我已将页面上的 javascript 剥离为仅加载 jQuery 并运行此命令,但问题仍然存在。

看到这个 jsFiddle,警报没有弹出,这意味着 javascript 引擎之前卡在了线上。

帮助表示赞赏。

4

1 回答 1

36

It doesn't make sense to try to add an element to the start of the document object. It isn't an HTMLElementNode. As far as I know, you can't give it additional children at all.

If you want to add a div element to the start of something, then the highest node that is allowed to contain it is the body element, so use:

$(document.body).prepend

… instead.

于 2013-05-28T06:31:58.950 回答