在网站上打印当年的最短途径 [英] Shortest way to print current year in a website

查看:125
本文介绍了在网站上打印当年的最短途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新几百个在页脚中具有硬编码版权日期的静态HTML页面。我想用一些每年会自动更新的JavaScript替换它。

I need to update a few hundred static HTML pages that have the copyright date hard coded in the footer. I want to replace it with some JavaScript that will automatically update each year.

目前我正在使用:

<script type="text/javascript">var year = new Date();document.write(year.getFullYear());</script>

这是否足够短?

推荐答案

这是我能得到的最短的:

Here's the shortest I can get it:

<script>document.write(new Date().getFullYear())</script>

这适用于我遇到的所有浏览器。

That will work in all browsers I've run across.

我如何到达那里:


  • 您只需拨打 getFullYear 直接在新创建的日期上,不需要变量。 new Date()。getFullYear()可能看起来有点奇怪,但它是可靠的: new Date()部分首先完成,然后是 .getFullYear()

  • 你可以删除类型,因为JavaScript是默认值;这甚至记录为 HTML5规范的一部分,可能在这种情况下要写出浏览器已经做过的事情。

  • 你可以在最后删除分号以获得一个额外保存的字符,因为JavaScript有自动分号插入,这是一个功能我通常鄙视并反对,但在这个特定用例中它应该足够安全。

  • You can just call getFullYear directly on the newly-created Date, no need for a variable. new Date().getFullYear() may look a bit odd, but it's reliable: the new Date() part is done first, then the .getFullYear().
  • You can drop the type, because JavaScript is the default; this is even documented as part of the HTML5 specification, which is likely in this case to be writing up what browsers already do.
  • You can drop the semicolon at the end for one extra saved character, because JavaScript has "automatic semicolon insertion," a feature I normally despise and rail against, but in this specific use case it should be safe enough.

这很重要请注意,这仅适用于启用了JavaScript的浏览器。理想情况下,这可以更好地作为一年一次的离线批处理作业( sed 脚本* nix等)处理,但如果你想要JavaScript解决方案,我认为这是尽可能短。 (现在我走了,试探命运。)

It's important to note that this only works on browsers where JavaScript is enabled. Ideally, this would be better handled as an offline batch job (sed script on *nix, etc.) once a year, but if you want the JavaScript solution, I think that's as short as it gets. (Now I've gone and tempted fate.)

这篇关于在网站上打印当年的最短途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆