对于带有属性的标签,在 document.write 中使用的正确语法是什么?

sem*_*d3r 1 javascript document.write

我在 JavaScript 的document.write方法中使用以下代码:

<script type="text/javascript">
    document.write("<font color="blue">["+time()+"]</font>");
</script>
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。我该如何修复它?

Que*_*tin 5

这个问题与 HTML 没有直接关系,而只是与字符串文字在 JavaScript(以及几乎所有其他编程语言)中的工作方式有关。如果您想"在 JavaScript 字符串中使用由字符分隔的字符",则必须对其进行转义:\"。或者,用于'分隔字符串或属性值。

document.write("<font color=\"blue\">["+time()+"]</font>");
document.write('<font color="blue">['+time()+"]</font>");
document.write("<font color='blue'>["+time()+"]</font>");
Run Code Online (Sandbox Code Playgroud)

也就是说,使用document.write通常生成 HTML 并不是一个好主意(它仅在加载时有效,通常最好用更可靠的服务器端代码或更可重用的DOM操作来替换))并且该font元素已被弃用。