document.write()的替代方案

时间:2018-03-16 19:51:46

标签: javascript

有人告诉我,最好尽量避免使用document.write()。那你怎么建议我处理这段代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Debug</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script>
    function writeTimesTable(num) {
      for(let i = 1; i < 13; i++ ) {
        let writeString = i + " * " + num + " = ";
        writeString = writeString + (i * num);
        writeString = writeString + "<br />";
        document.write(writeString);
      }
    }

  </script>
</head>
<body>
  <script>
    for(let i = 1; i <= 13; i++ ) {
      document.write("<p>")
      writeTimesTable(i) 
      document.write("</p>")

    }
  </script>
</body>
</html>

我尝试了innerHTML,但我不断获得undefined

这是我在

之后使用的代码
function writeTimesTable(num) {
  for(let i = 1; i < 10; i++ ) {
    let writeString = i + " * " + num + " = ";
    writeString = writeString + (i * num);
    writeString = writeString + "<br />";
    document.write(writeString);
  }
}


function newTable() {
  for(let i = 1; i <= 10; i++ ) {
    let para = document.getElementById("paragraph");
    para.innerHTML = writeTimesTable(i)    

  }
}

1 个答案:

答案 0 :(得分:0)

只需使用元素 .innerHTML =内容即DOM操作