在 document.write 中用于具有属性的标签的正确语法是什么

What is the right syntax to use in document.write for tags with attributes?

本文关键字:标签 是什么 语法 属性 write document 用于      更新时间:2023-09-26

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

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

但这似乎行不通。请指导我。

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

document.write("<font color='"blue'">["+time()+"]</font>");
document.write('<font color="blue">['+time()+"]</font>");
document.write("<font color='blue'>["+time()+"]</font>");

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

<script type="text/javascript">
      document.write("<font color='"blue'">[" + time() + "]</font>");
</script>

<script type="text/javascript">
      document.write('<font color="blue">[' + time() + ']</font>');
</script>

请注意,time 在 JavaScript 中不作为函数存在 — 我假设您在上面创建了一个未包含在代码片段中的函数。此外,除非你只是在试验,否则你不应该真的将document.write用于任何事情。您可以使用Firefox的Firebug或Safari/Chrome Web Inspector中的console.log来测试所有这些,这将比整页刷新更快。还注意到我如何在+标志的两侧添加空格:更容易阅读。

你可以使用css而不是html,它非常简单

window.document.write("<span style='"color:blue;font-size: 5em;'">hello " + variable + "<'/span>");
var color = 'blue';     
document.write("<font color="+color+">["+time()+"]</font>");

 document.write("<font color='blue'>["+time()+"]</font>");