0

我有一个按钮,可以使用打开一个新的空白窗口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,但问题是(我认为)没有使用打开的新窗口的 ID window.open

相反,乘法表会打印在原始窗口上,并且在新的弹出窗口中,会显示“未定义”消息。这是有道理的,同样是因为嵌套document.write的 s。


两个问题:

  1. 如何修复这个嵌套document.write并仍然让它工作?
  2. 有没有办法使用 将 ID 分配给新窗口window.open

此外,我查看了这个 SO 帖子:document.write 嵌套在 document.write 中,但唯一的答案就是不使用document.write

先感谢您。

4

1 回答 1

0

除了不要使用 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>

于 2020-07-17T13:03:01.213 回答