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

目前我正在使用:

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

就这么短了吗?


当前回答

这个答案与Ray的答案相似,但使用了模板文字和文本回退

<p>&copy;
  <span id="copyright-year">2021</span>
  Company Name
</p>

<script>
  document.getElementById("copyright-year").innerHTML = `${new Date().getFullYear()}`;
</script>

©2022公司名称

document.getElementById("copyright-year").innerText = `${new Date().getFullYear()}`;

同样适用。

其他回答

满一年:

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();
        }
    })();
});

React.js, 我们可以在单行中使用-

    return 
    <div className="copyright">Company 2015-{new Date().getFullYear()}</div>
    

Easy-peasy !

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

这个答案与Ray的答案相似,但使用了模板文字和文本回退

<p>&copy;
  <span id="copyright-year">2021</span>
  Company Name
</p>

<script>
  document.getElementById("copyright-year").innerHTML = `${new Date().getFullYear()}`;
</script>

©2022公司名称

document.getElementById("copyright-year").innerText = `${new Date().getFullYear()}`;

同样适用。