【问题标题】:How can one create a dynamic copyright date without document.write() in JavaScript?如果没有 JavaScript 中的 document.write(),如何创建动态版权日期?
【发布时间】:2017-05-01 03:46:42
【问题描述】:

如何在 JavaScript 中不使用document.write() 来获取和打印当前年份?

这是针对页脚中典型的版权行;例如,© 2017 Stack Overflow。

现在我正在使用标准的document.write() 方法。

document.write(new Date().getFullYear());

【问题讨论】:

  • document.getElementById("someElementId").innerHTML = new Date().getFullYear();? (这里的日期/版权部分无关紧要,对吧?就像,你只需要能够显示来自 JS 的任何值?)
  • 这让我走上了正确的道路。谢谢!
  • 使用 document.write 有什么问题(除了取决于客户端设置为正确的年份)?
  • @RobG Lighthouse 返回错误:[Violation] Avoid using document.write().,因为它会对性能产生不利影响。

标签: javascript date document.write


【解决方案1】:

是的,你可以使用一个元素:

<p>© Stack Overflow <span id="year"> </span></p>

像这样为你的 JS 添加一个链接:

<script src="js/app.js"></script>

在这个文件中你可以做:

var date = new Date().getFullYear();

document.getElementById("year").innerHTML = date;

您也可以像这样简单地使用 php:

<?php echo date("Y"); ?>

如果您使用的是 php,请确保将文件 ext 更改为 PHP。

【讨论】:

  • 对于初学者,如果你使用 PHP,你也需要一个 PHP 服务器 :)
【解决方案2】:

document.getElementById("current-year").innerHTML = new Date().getFullYear();
&lt;span id="current-year"&gt;&lt;/span&gt;

【讨论】:

  • 非常简单和接近,喜欢它!
【解决方案3】:

使用 JavaScript:

Copyright &copy <script type="text/javascript"> document.write(new Date().getFullYear());</script> [companyName] Communications Inc. All rights reserved.

如果你在 here 这样的地方编译上面的代码,你会得到一个输出为 2021 但例如,如果你有一个footer.vm 文件:

<div id="footerLinks" style="clear:left; text-align:left; color:#282828">
    Copyright &copy <script type="text/javascript"> document.write(new Date().getFullYear());</script> DigiVie Communications Inc. All rights reserved.
  </div>

这个是 PHP 的:

&copy; <?php
  $fromYear = 2008;
  $thisYear = (int)date('Y');
  echo $fromYear . (($fromYear != $thisYear) ? '-' . $thisYear : '');?> CompanyName.

【讨论】:

    【解决方案4】:

    上面由 user3731460 发布并由 user663031 编辑的非常简单的解决方案效果很好。

    在此页面上的帖子中,一位评论者问“使用 document.write 有什么问题(除了取决于客户端设置为正确的年份)?”

    我不知道 2017 年的原因(最初在这里提出问题时),但现在(2020 年 10 月),chrome 的灯塔扩展给出了警告“避免 document.write,因为它可以将页面加载延迟数十秒。谷歌鼓励用户体验的方式,我可以看到谷歌可能会在某些时候惩罚 document.write 的使用。

    【讨论】:

    • 评论的重点是让 OP 思考为什么 document.write 在这种情况下可能是好是坏。不使用它是因为“Google 开发工具说不要使用它”不是一个合乎逻辑的论点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多