【问题标题】:jQuery not working in child window?jQuery 在子窗口中不起作用?
【发布时间】:2012-05-16 05:22:41
【问题描述】:

当我写作时:

var x = window.open('','','width=480,height=500');
x.document.write('
<html>
<head>
<link rel="stylesheet" type="text/css" href="chat.css" / >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"><' +'/script>
<script type="text/javascript">
alert("hi");
<' + '/script>
</head>
<body><p>hi</p></body>
</html>');

我收到警报。

但如果我这样做——

 x.document.write('
<html>
<head>
<link rel="stylesheet" type="text/css" href="chat.css" / >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
<' +'/script>
<script type="text/javascript">
$(function(){
alert("hi");
});
<' + '/script>
</head>
<body><p>hi</p></body>
</html>');

然后就不行了。它什么也不做。我整晚都在想办法解决这个问题。有什么想法吗?

【问题讨论】:

    标签: jquery window cross-window-scripting


    【解决方案1】:

    这是因为 jQuery 从不触发 DOM 就绪事件,除非您在写入文档后正确地.close()

    var x = window.open('','','width=480,height=500'),
    x.document.write('all your html and script here');
    x.document.close();
    

    到期信用:window.open and $(document).ready

    【讨论】:

    • 哦,jk。顺便说一句,我只是为了可读性才这样格式化它——实际上并不是这样写的。
    • 发布时不要更改代码。无论如何,我在 jsfiddle 中尝试了该代码,它工作正常。
    • @Aerovistae 用小提琴链接更新了答案
    • 好吧,如果我不把这些行分开,那么你读起来会很费劲。无论如何,如上所述,行分隔不是问题——我的实际代码只是将它放在一个大块中。不过还是谢谢。
    • @Aerovistae 我明白了,你检查过 Fiddle 了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-12-06
    相关资源
    最近更新 更多