我应该使用 document.writeln 吗?

should I use document.writeln?

下面的 javascript 脚本虽然可以加载所需的结果,但是否有问题? document.writeln 应该被 document.write 甚至其他一些方法代替吗?我从网上得到了这个想法 http://www.wetlandpark.gov.hk/en/

function getheaderHTML() {
  document.writeln('  <div id="nav">');
  document.writeln('    <a href="index.html">number 1</a>|<a href="students.html">number 2</a>');
  document.writeln('  </div>');
  document.writeln('  <div id="header">');
  document.writeln('    <img src="header.jpg" alt="testing" width=100% height=260>');
  document.writeln('  </div>');
}

function getfooterHTML() {
  document.writeln('  <div id="footer">');
  document.writeln('    &#169;2016');
  document.writeln('  </div>');
}
getheaderHTML();
getfooterHTML();

write()writeln()没有太大区别。唯一的区别是 writeln() 在每个语句后添加一个新行。

但是对于上面的代码,换行与否并没有太大的区别,因为 空格在 HTML 中被忽略了。

同时使用 document.writewriteln 也不是一个好主意。我建议您使用 2 div 作为占位符来注入您的 headerfooter HTML。

我只建议将您的代码重构为

function getheaderHTML() {
  var content = '<div id="nav"><a href="index.html">number 1</a>|<a href="students.html">number 2</a> </div><div id="header"> <img src="header.jpg" alt="testing" width=100% height=260></div>';
  
  document.getElementById('pageheader').innerHTML = content;
}

function getfooterHTML(){
  var content = '<div id="footer">&#169;2016</div>';
  
  document.getElementById('pageFooter').innerHTML = content;
}

getheaderHTML();
getfooterHTML();
<div id="pageheader">

</div>

<div id="BodyContainer">

</div>

<div id="pageFooter">

</div>