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

目前我正在使用:

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

就这么短了吗?


当前回答

满一年:

document.getElementById(“getyear”).innerHTML = (new Date().getFullYear()); <span id=“getyear”></span>

其他回答

这是我能想到的使用纯JavaScript的最佳解决方案。您还可以在CSS中为元素设置目标样式。只要把年份加进去,它就会自动更新。

//Wait for everything to load first
window.addEventListener('load', () => {
    //Wrap code in IIFE 
    (function() {
        //If your page has an element with ID of auto-year-update the element will be populated with the current year.
        var date = new Date();
        if (document.querySelector("#auto-year-update") !== null) {
            document.querySelector("#auto-year-update").innerText = date.getFullYear();
        }
    })();
});

如果你在你的网站上多次需要当前年份,你可以这样做:

document.querySelectorAll(“copy-year”)。forEach(el => { 埃尔。textContent = ' ${el。textContent} - ${new Date().getFullYear()} '; }); 版权所有公司<copy-year>1234</copy-year>©

我知道,这不是最短的方法,但它真的很有效。

PS:你需要有JS在你的页面底部或使用延迟属性的脚本标签。

这里有一个最短最负责任的版本,甚至适用于AD和BC。

(滚筒滚……)

<script>document.write(Date().split` `[3])</script>

就是这样。比接受的答案短6字节。

如果你需要兼容ES5,你可以满足:

<script>document.write(Date().split(' ')[3])</script>

TJ的回答很好,但我遇到了一个场景,我的HTML已经呈现,文档。写脚本将覆盖所有的页面内容,只有日期年。

对于这种情况,您可以使用以下代码将一个文本节点附加到现有元素:

<div>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>

Easy-peasy !

< p >软件是 < script type = " text / javascript " > 文档。写(新的日期().getFullYear ()); > < /脚本 < / p >