【发布时间】:2020-11-07 06:55:28
【问题描述】:
我有一个按钮,可以使用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。
两个问题:
- 如何修复这个嵌套的
document.write并使其仍能正常工作? - 有没有办法使用
window.open为新窗口分配一个ID?
另外,我看了这个 SO 帖子:document.write nested in document.write,但唯一的答案就是不要使用document.write。
提前谢谢你。
【问题讨论】:
-
答案就是不要使用 document.write。
-
我给你做了一个sn-p。我必须在
</button>之后添加一个",但还有其他事情发生
标签: javascript window.open document.write new-window