【发布时间】:2015-01-04 19:06:56
【问题描述】:
我正在浏览 JavaScript The Complete Reference 3rd Edition 中给出的示例。
O/P可见here,由作者给出。
<body>
<h1>Standard Whitespace Handling</h1>
<script>
// STRINGS AND (X)HTML
document.write("Welcome to JavaScript strings.\n");
document.write("This example illustrates nested quotes 'like this.'\n");
document.write("Note how newlines (\\n's) and ");
document.write("escape sequences are used.\n");
document.write("You might wonder, \"Will this nested quoting work?\"");
document.write(" It will.\n");
document.write("Here's an example of some formatted data:\n\n");
document.write("\tCode\tValue\n");
document.write("\t\\n\tnewline\n");
document.write("\t\\\\\tbackslash\n");
document.write("\t\\\"\tdouble quote\n\n");
</script>
<h1>Preserved Whitespace</h1>
<pre>
<script> // in Eclipse IDE, at this line invalid location of tag(script)
// STRINGS AND (X)HTML
document.write("Welcome to JavaScript strings.\n");
document.write("This example illustrates nested quotes 'like this.'\n");
document.write("Note how newlines (\\n's) and ");
document.write("escape sequences are used.\n");
document.write("You might wonder, \"Will this nested quoting work?\"");
document.write(" It will.\n");
document.write("Here's an example of some formatted data:\n\n");
document.write("\tCode\tValue\n");
document.write("\t\\n\tnewline\n");
document.write("\t\\\\\tbackslash\n");
document.write("\t\\\"\tdouble quote\n\n");
</script>
</pre>
</body>
(X)HTML 自动将多个空白字符“折叠”成一个空白。因此,例如,在您的 HTML 中包含多个连续的选项卡只会显示为一个空格字符。在此示例中,pre 标签 用于告诉浏览器 文本已预先格式化,不应折叠其中的空白。同样,我们可以使用 CSS 空白属性 来修改标准的空白处理。使用 pre 可以让示例中的选项卡在输出中正确显示。
那么,如何摆脱这个警告,我真的需要关心这个吗?我认为我错过了一些东西,因为我认为作者的直觉没有错?
【问题讨论】:
-
那本书有 11 年历史了。我很惊讶它还没有变成化石。为自己找到一个不使用
document.write()的更新参考。现在没有明智的 JS 开发人员会编写这样的代码。这不是问题。 -
他们会怎么写呢?我的意思是演示“hello world”示例。
-
@jonasnas 一种方法是在 HTML 中创建一个带有 ID 的
div并将 ID 添加到pre元素,使用脚本使用变量和字符串连接来构建字符串,然后使用getElementById()和.innerHTML将字符串分配给页面元素。我不认为你会找到一本在过去 5 年中使用document.write()创建页面内容的受人尊敬的 JS 介绍书(可能将内容写入子窗口除外)。 -
@JLRishe:我已经更新了我拥有的电子书信息。
-
@JLRishe 我个人不介意在“hello world”示例中使用 document.write。就像在这种情况下,本书的主题是关于 pre 标签,而不是 js 的最佳实践。附言即使在“权威指南”书中,它也提到使用 dom 函数是更好的方法(就像你建议的那样),但是在同一本书中有一些例子,作者使用 document.write('some tag') 只是为了演示其他功能的某些行为书谈
标签: javascript html css