0

更新:感谢大家的回复。我没有意识到 document.write() 已被弃用。在学习栏上再添一个档次。我将接受此处发布的建议,但保留原始问题,以便给出的答案在原始问题的上下文中有意义。


我正在编写一些相当长的 write() 参数,并且考虑到语法、可读性和性能,我正在尝试确定以下哪个示例最好遵循。我是不是该

一种。将它们全部放在一行上:

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable);

</script>

湾。通过添加换行符来分解它们以提高可读性:

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" 
        + someVariable
        + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" 
        + someVariable);

</script>

C。通过使用多个变量来分解它们:

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    var partOne = "<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>"; 
    var partTwo = "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>"; 

    document.write(partOne + someVariable + partTwo + someVariable);

</script>

提前致谢。

4

3 回答 3

3

我的直觉反应是:不要那样做。(您的示例很差,您不应该在行为层中编写大量内容。)

每当你必须这样做时,要么连接:

var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' +
    ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' +
    'qersdfasdfasdfasdfasdf';
document.write(longVar);

或者,如果它变得非常长,则使用加入数组可能会提高性能:

var longVar = [
    'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf',
    ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ',
    'qersdfasdfasdfasdfasdf'
].join('');
document.write(longVar);
于 2008-10-27T02:40:31.843 回答
0

我会写它,但是它将最容易阅读和维护。然后测试性能。如果速度太慢,请尝试逐步改进算法,直到速度可以接受。

所以提高性能的想法: - 确保脚本被缩小。- 在服务器上进行尽可能多的预处理并提供“已处理”脚本。

通过使用缩小工具(例如 jsMin),您不会因使用空格和换行符以提高可读性而遇到任何问题。

于 2008-10-27T02:45:49.367 回答
0

-- 这是一个不好的例子,document.write()因为它属于 90 年代,并且在 1998 年随着 HTML4 的引入而被弃用......

如果您在服务器端有任何东西,最好在那里处理代码生成......

关于连接字符串的问题,我同意没有眼睑!-)

编辑(29/10)

作为对评论的评论(我需要代码符号)

<script type="text/javascript">
  window.onload = function(){
    var newD = document.createElement("div");
    newD.appendChild(document.createTextNode("Hello World"));
    document.getElementsByTagName("body")[0].appendChild(newD);
  }
</script>

这样任何东西都被插入到文档中......

于 2008-10-27T03:42:27.740 回答