Jquery Prepend:无法调用 null 的方法“createDocumentFragment”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16785227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Prepend: Cannot call method 'createDocumentFragment' of null
提问by JNF
During page startup I'm trying to add an element to the DOM.
在页面启动期间,我试图向 DOM 添加一个元素。
I have the following code:
我有以下代码:
$(document).ready(function () {
$(document).prepend("<div id=new_div style=z-index:1;></div>");
});
I've tested this on FF21, Chrome27 and IE10. They all return the error mentioned in the title (exact wording is from the Chrome debugger).
我已经在 FF21、Chrome27 和 IE10 上对此进行了测试。它们都返回标题中提到的错误(确切的措辞来自 Chrome 调试器)。
Debugging on jquery-1.10.0.js, I tracked down the problem to line 5998 where
在 jquery-1.10.0.js 上调试,我将问题追踪到第 5998 行,其中
safeFrag = document.createDocumentFragment()
Apparently document is null. Going up the stack trace to domManip
on line 6249 the object is passed as this[ 0 ].ownerDocument
, which is null.
显然文档为空。将堆栈跟踪向上移动到domManip
第 6249 行,该对象作为 传递this[ 0 ].ownerDocument
,它为空。
I've stripped the javascript on the page to just loading jQuery and running this command, and the issue persists.
我已将页面上的 javascript 剥离为仅加载 jQuery 并运行此命令,但问题仍然存在。
See this jsFiddle, the alert doesn't pop, meaning the javascript engine got stuck on the line before.
看到这个 jsFiddle,警报没有弹出,这意味着 javascript 引擎之前卡在了线上。
Help appreciated.
帮助表示赞赏。
回答by Quentin
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.
尝试在document
对象的开头添加元素是没有意义的。它不是 HTMLElementNode。据我所知,你根本不能给它额外的孩子。
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:
如果要将 div 元素添加到某物的开头,则允许包含它的最高节点是 body 元素,因此请使用:
$(document.body).prepend
… instead.
… 反而。