Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

javascript - 在网站上打印当前年份的最短方法(Shortest way to print current year in a website)

I need to update a few hundred static HTML pages that have the copyright date hard coded in the footer.

(我需要更新几百个静态HTML页面,这些页面的页脚中已硬编码了版权日期。)

I want to replace it with some JavaScript that will automatically update each year.

(我想用每年都会自动更新的JavaScript替换它。)

Currently I'm using:

(目前,我正在使用:)

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

Is this as short as it gets?

(这是那么短吗?)

  ask by tpow translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(这将适用于我所运行的所有浏览器。)

How I got there:

(我如何到达那里:)

  • You can just call getFullYear directly on the newly-created Date , no need for a variable.

    (您可以直接在新创建的Date上直接调用getFullYear ,而不需要变量。)

    new Date().getFullYear() may look a bit odd, but it's reliable: the new Date() part is done first, then the .getFullYear() .

    (new Date().getFullYear()可能看起来有些奇怪,但是很可靠:首先完成new Date()部分,然后完成.getFullYear() 。)

  • You can drop the type , because JavaScript is the default;

    (您可以删除type ,因为JavaScript是默认设置。)

    this is even documented as part of the HTML5 specification , which is likely in this case to be writing up what browsers already do.

    (这甚至被记录为HTML5规范的一部分,在这种情况下,很可能是在写出浏览器已经做过的事情。)

  • 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有“自动插入分号,”一个功能,我常轻视和对铁路,但在这种特定情况下使用它应该是足够安全的。)

It's important to note that this only works on browsers where JavaScript is enabled.

(重要的是要注意,这仅适用于启用了JavaScript的浏览器。)

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.

(理想情况下,最好将其作为脱机批处理作业(* nix上的sed脚本等)每年处理一次,但是如果您想要JavaScript解决方案,我认为它就这么短。)

(Now I've gone and tempted fate.)

((现在,我走了,去吸引命运。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...