我正在用 JavaScript/jQuery 开发一个小项目。
为了显示在 javascript 中完成的计算结果,我想打开一个包含一些预定义内容的新窗口并修改这些内容以显示结果:我使用这样的代码:
var resultwindow = window.open('result.html')
var doc = $('body', resultwindow.document);
doc.append("<p>Result</p>")
这是行不通的,因为当我附加内容时结果文档尚未加载,所以它被“result.html”的内容覆盖。
我也试过
$(resultwindow.document).ready(function() {
// ... Fill result document here
})
和
$(resultwindow.document).load(function() {
// ... Fill result document here
})
但 ready()
仅对当前文档起作用(如果当前文档已经加载,则立即调用),而 load
不会在全部。
也许有人能给我指出正确的方向。提前致谢!
编辑:
我最终通过在 Javascript 中“手动”创建新文档解决了这个问题,例如:
w = window.open('','newwinow','width=800,height=600,menubar=1,status=0,scrollbars=1,resizable=1);
d = w.document.open("text/html","replace");
d.writeln('<html><head>' +
'<link rel="stylesheet" type="text/css" href="style.cs"/></head>' +
+'<body></body></html>');
// use d to manipulate DOM of new document and display results
如果我今天做同样的事情(两年后的经验),我会使用一些 Javascript 模板库,比如 Handlebars维护模板并将其编译为 javscript。
最佳答案
您的 load
调用不起作用,因为您正在尝试处理 document
的加载,并且此时 document 可能甚至不存在。这意味着您将 null 传递给 jQuery,它会优雅地忽略您。改为处理原始窗口引用的加载事件,然后你就可以开始了......
var win = window.open("result.html");
$(win).load(function() {
$("body").append("<p>Result</p>");
});
关于javascript - 使用 jquery 创建新窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3990340/