更新:感谢大家的回复。我没有意识到 document.write() 已被弃用。为学习栏目再添一个档次。我将采纳此处发布的建议,但保留原始问题,以便给出的答案在原始问题的上下文中有意义。
<小时/>我正在编写一些相当长的 write() 参数,并考虑语法、可读性和性能,尝试确定以下哪个示例最适合遵循。我应该吗
a.将它们全部放在一行上:
<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>
b.通过添加换行符来分解它们,以提高可读性:
<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>
提前致谢。
最佳答案
我的直觉 react 是:不要这样做。 (你的例子很糟糕,你不应该在行为层中编写大块内容。)
每当你必须这样做时,要么连接:
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);
关于javascript - 处理长 write() 参数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/238941/