在新的window.open中运行Javascript [英] Running Javascript in new window.open

查看:157
本文介绍了在新的window.open中运行Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行此功能以打开一个新窗口。

I'm running this function to open a new window.

function htmlNewWindow(id) {
    var html = $(id).html();
    var newWindow = window.open('');
    newWindow.document.body.innerHTML =  '<html><head><title>Hi</title>  <script src="js/myScript.js"></script> </head>' + html;    
}

此操作成功创建了一个包含HTML的新窗口。我有一堆HTML标记,单击这些标记可以运行一个名为Foo1的函数。我尝试将Foo1的全部功能打印到新的HTML文档中,并尝试将Foo1放入myScript.js中。我在新窗口中的脚本标签中都看到了Foo1,但是都没有加载,因为它们只是作为HTML写入新页面的。

This successfully creates a new window with the HTML in it. I have a bunch of HTML tags which when clicked run a function called Foo1. I've tried printing the entire function of Foo1 to the new HTML document, and tried putting Foo1 inside myScript.js. I see both Foo1 inside a script tag in the new window, and but neither are loaded since they are just written to the new page as HTML.

推荐答案

添加了 .innerHTML 的脚本不会执行。您需要创建一个脚本节点,并将其附加到窗口的DOM中。

Scripts added with .innerHTML aren't executed. You need to create a script node and append it to the window's DOM.

$("#button").click(newWindow);

function newWindow(id) {
  var html = $(id).html();
  var win = window.open('');
  win.document.head.innerHTML = '<title>Hi</title></head>';
  win.document.body.innerHTML = '<body>' + html + '</body>';
  var script = document.createElement('script');
  script.src = 'js/myScript.js';
  win.document.head.appendChild(script);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click me</button>

这不在Stack Snippet的沙箱,这是一个有效的 jsfiddle

This doesn't run in Stack Snippet's sandbox, here's a working jsfiddle.

这篇关于在新的window.open中运行Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆