如何打开一个新窗口并使用jQuery将html插入其中?

Fai*_*een 66 html javascript jquery

我试图从javascript打开一个新窗口但没有插入到html中:

var callScriptText = $('#callScriptText').html();
var url = '/Action/CallScript/?callScript=';

// Open the current call script in a new window
var openWindow = window.open(url, 'callScriptPopup', 'width = 500, height = 500');
$(openWindow).html(callScriptText);
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么?

Jua*_*nma 111

这是一个使用jQuery打开包含内容的新窗口的示例

<script>
function nWin() {
  var w = window.open();
  var html = $("#toNewWindow").html();

    $(w.document.body).html(html);
}

$(function() {
    $("a#print").click(nWin);
});?
</script>

<div id="toNewWindow">
    <p>Your content here</p>
</div>

<a href="javascript:;" id="print">Open</a>?
Run Code Online (Sandbox Code Playgroud)

编辑:对于那些说这段代码不起作用的人,这里有一个jsfiddle尝试它http://jsfiddle.net/8dXvt/

  • 有没有可能插入孔html(像下面的结构而不是从正文中放入`&lt;html&gt;&lt;head&gt;&lt;title&gt;&lt;/title&gt;&lt;script&gt;&lt;/script&gt;&lt;body&gt;&lt;/body&gt;&lt;/ html&gt;`) (2认同)

小智 84

试试这个:

var x=window.open();
x.document.open();
x.document.write('content');
x.document.close();
Run Code Online (Sandbox Code Playgroud)

我觉得它适用于Chrome和IE.

  • 这比jQuery解决方案效果更好,因为您可以编写整个HTML文档,包括doctype和`<head>`标记. (10认同)
  • 完善.谢谢. (4认同)
  • 在我的 chrome 版本 51.0.2704.84 m 中不起作用。window.open() 之后的 x 返回 undefined 所以它没有文档 (2认同)

Sab*_*ste 25

以@Emre的答案为基础.

使用javascript,你可以链,所以我只是将代码修改为:

var x=window.open();
x.document.open().write('content');
x.close();
Run Code Online (Sandbox Code Playgroud)

此外,要强制它到新窗口(而不是新选项卡),请给出第一行尺寸.但它必须是第三个论点.所以将第一行改为:

var x=window.open('','','width=600, height=600');
Run Code Online (Sandbox Code Playgroud)