2015-02-06 47 views
0

我目前使用document.write来将html注入到我的框架中。我使用Backbone,Marionette,require.js,jQuery。避免document.write?任何替代品?

我想避免使用document.write,因为它有性能和浏览器的影响。

请提出替代方案。

我当前的代码:

var html = this.compilePageHtml(); //We get some HTML code 
    this._previewWindow = window.open("about:blank", "PreviewWindow","width=320, height=570, scrollbars=yes"); 
    this._previewWindow.document.write(html); //Loads HTML in new window popup 
+2

为什么不使用'的.html()',而不是..的 – qtgye 2015-02-06 05:40:58

+0

可能重复(http://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write) – 2015-02-06 05:46:54

+0

在jQuery中:$(this._previewWindow.document).html(html); – MaxZoom 2015-02-06 05:52:48

回答

2

你可以使用上的新窗口的身体.innerHTML财产。

this._previewWindow = window.open("about:blank", "PreviewWindow","width=320, height=570, scrollbars=yes"); 
this._previewWindow.document.body.innerHTML = html; 

演示:?[?什么是替代使用document.write] http://jsfiddle.net/jfriend00/g9e8rg7h/

+0

这将替换body元素中的html,而它应该是文档。 – MaxZoom 2015-02-06 05:54:01

+1

@MaxZoom - 它取决于OP的html是什么(他们没有透露)。一个新的窗口/文档被赋予一个框架体,所以这段代码将设置正文HTML。是的,你也可以设置document.documentElement HTML。 – jfriend00 2015-02-06 05:59:06

+0

我添加了'this._previewWindow.document.close();'它瞬间加载(而不是4-5秒的滞后),但是我得到了jquery.mobile加载页面的错误。这是div'

Error Loading Page

'一切似乎都正常,但我不明白为什么我有这个错误。 – VRD 2015-02-06 09:01:26