如何将JavaScript写入单独的窗口? [英] How to write JavaScript to a separate window?

查看:89
本文介绍了如何将JavaScript写入单独的窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JavaScript打开了一个新窗口:

I have opened a new window with JavaScript:

var newwin = window.open('','preview','width=600,height=500');

现在我想在窗口写一些JavaScript:

Now I want to write some JavaScript to the window:

newwin.document.write("<script type='text/javascript'>alert('Hi!');<" + "/script>");
newwin.document.close();

然而,脚本永远不会被执行。我做错了吗?

However, the script never gets executed. Am I doing something wrong?

更新:好的,现在我有一部分工作了。这是我目前的代码:

Update: Okay, now I got part of it working. Here is the current code I have:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type='text/javascript'>

function SetContent()
{
    $('#content').html('New Text');
}

function dowin()
{
    var newwin = window.open('','preview','width=600,height=500');

    newwin.document.write('<div id="content"></div><b>This should be replaced...</b>');
    newwin.document.close();

    var script = newwin.document.createElement("script");
    script.type = "text/javascript";
    script.src = 'jquery.js';
    newwin.document.body.appendChild(script);

    var script2 = newwin.document.createElement("script");
    script2.type = "text/javascript";
    script2.textContent = "(" + SetContent + ")();";
    newwin.document.body.appendChild(script2);
}

</script>
</head>
<body>
<button onclick='dowin();'>Open</button>
</body>
</html>

它应该改变 div 但正如你所看到的,它没有。

It's supposed to change the content of the div but as you can see, it doesn't.

推荐答案

你的代码在我的Firefox 3.7,Opera 10上正常运行, IE6,但您可以通过使用DOM函数尝试不同的方法。

Your code running ok on my Firefox 3.7, Opera 10, and IE6, but you could try different approach by using DOM functions.

var newwin = window.open('','preview','width=600,height=500');

function sayHi(){
    alert('Hi!');
}

var script = newwin.document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + sayHi + ")();";
newwin.document.body.appendChild(script);

如果它不起作用,你应该仔细检查浏览器上的弹出窗口拦截器或javascript阻止程序。

If its not working, you should double check popup blockers or javascript blockers on your browser.

这篇关于如何将JavaScript写入单独的窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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