重构使用window.open而不是write()的函数以使用DOM

Refactoring a function that uses window.open to use the DOM rather than write()

本文关键字:函数 DOM open window 重构 write      更新时间:2023-09-26

我有一个使用window.open()生成动态弹出窗口的应用程序。不幸的是,我在使用标准DOM函数(createElementappendChild)创建新窗口的内容时遇到了问题,我转而使用document.write()来生成页面。

具体地说,我该怎么做:

function writePopup()
{
    var popup = window.open("", "popup", "height=400px, width=400px");
    var doc = popup.document;
    doc.write("<html>");
    doc.write("<head>");
    doc.write("<title>Written Popup</title>");
    doc.write("</head>");
    doc.write("<body>");
    doc.write("<p>Testing Write</p>");
    doc.write("</body>");
    doc.write("</html>");
    doc.close();
}

对于使用DOM创建相同弹出窗口的函数?

编辑:我确实考虑过使用一个绝对定位的元素来模拟弹出窗口,尽管它看起来更好,但用户需要能够打印显示的信息。

只需进行快速测试,我就可以让doc将DOM创建的HTML附加到弹出窗口中,如下所示:

var popup = window.open("", "popup", "height=400px, width=400px"); 
var doc = popup.document.documentElement;
var p = document.createElement("p"); 
p.innerHTML = "blah"; 
doc.appendChild(p);

我知道我的例子产生了完全无效的HTML,但它是有效的(显然测试有限)。

.innerHTML的一个转储应该比无数行的document.write()执行得更好;

我会根据需要构建DOM,并使用进行转储

doc.innerHTML = newDOM;

仍然有点古怪,但比document.write()要好;

我已经使用document.write()来生成页面。

我认为您可能至少需要使用一些document.write()来放置一个框架页面,然后才能与DOM:交互

doc.write('<!DOCTYPE ...><html><head></head><body></body></html>');
doc.close();
doc.body.appendChild(...);

在调用write()之前,新窗口的文档处于不确定状态,没有文档可与之交互。在你第一次调用document.write()之前,Firefox至少会放一个临时的框架文档,但我看不出它实际上在任何地方都有文档,所以最好不要依赖它。

var popup=window.open(","popup","height=400px,width=400px");

window.open.

中不需要"px"单位

为什么不使用库函数http://plugins.jquery.com/project/modaldialog而不是重新发明轮子?

[编辑]或

function writePopup(){
    var popup = window.open("", "_blank", "height=400px, width=400px");
    var doc = popup.document;
    doc.title = 'Written Popup';
    var p = doc.createElement('p');
    p.innerHTML = 'Testing Write';
    doc.body.appendChild(p);
}

是否可以有另一个生成动态内容的页面,并将其打开,传递标识您想要生成的内容的参数,而不是尝试写入新窗口?

您可以使用类似的东西

function writePopup(){
  var htmlString=[
    "<html>",
    "<head>",
    "<title>Written popup</title>",
    "</head><body>",
    "<p>Testing write</p>",
    "</body></html>"
  ].join("'n");
  window.open("data:text/html,"+encodeURIComponent(htmlString), "_blank", "height=400px, width=400px");
}