有没有办法修复window.open中的嵌套文档.write



我有一个按钮,它将使用window.open打开一个新的空白窗口,但会在上面写一个乘法表。

这是我的密码。

document.getElementById("p").innerHTML = "<button id = 'mult' type = 'button'>Multiplication Tables</button>";
document.getElementById("mult").onclick = function() {
newWindow()
};
document.getElementById("close").onclick = function() {
close()
};
function newWindow() {
var multiplyWindow = window.open("", "multiplicationTables", "width = 300, height = 200");
multiplyWindow.document.write(multiply());
}
function multiply() {
document.write("<center><table border='1px'>");
for (var a = 5; a < 11; a++) {
document.write("<tr style='height:40px'>");
for (var b = 5; b < 11; b++) {
document.write("<td style='width:40px'><center><font size='4'>" + a * b + "</center></font></td>");
}
document.write("</tr>");
}
}
<p id="p"></p>

我知道问题是因为当我运行multiply()函数时,我们正在嵌套一个document.write。我想过使用document.getElementById,但问题是(我认为(没有使用window.open打开的新窗口的ID。

相反,乘法表被打印在原始窗口上,而在新的弹出窗口中;未定义的";消息显示。这是有道理的,同样是因为嵌套的document.writes。


两个问题:

  1. 如何修复此嵌套的document.write并使其正常工作
  2. 有没有一种方法可以使用window.open为新窗口分配ID

此外,我看到了这篇SO文章:document.write嵌套在document.write中,但唯一的答案是不使用document.write

提前谢谢。

除了"请勿使用文档"。编写

你不能";巢;

更改

function multiply() {
document.write("<center><table border='1px'>");
for (var a = 5; a < 11; a++) {
document.write("<tr style='height:40px'>");
for (var b = 5; b < 11; b++) {
document.write("<td style='width:40px'><center><font size='4'>" + a * b + "</center></font></td>");
}
document.write("</tr></table>");
}
}

不是document.write而是返回html

function multiply() {
const html = []
html.push("<center><table border='1px'>");
for (var a = 5; a < 11; a++) {
html.push("<tr style='height:40px'>");
for (var b = 5; b < 11; b++) {
html.push("<td style='width:40px'><center><font size='4'>" + a * b + "</center></font></td>");
}
html.push("</tr>");
}
return html.join("")
}

function newWindow() {
const multiplyWindow = window.open("", "multiplicationTables", "width=300,height=200");
if (multiplyWindow) {
multiplyWindow.document.write(multiply());
multiplyWindow.document.close(); // important
}  
else alert("sorry, popups are blocked");
}
const p = document.getElementById("p");
p.innerHTML = "<button class='mult' type='button'>Multiplication Tables</button>";
p.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("mult")) newWindow()
})
<p id="p"></p>

最新更新