You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现页面同时展示当前年份与随机4位数字?

解决:年份前置的随机编号展示

你的代码问题出在这几个地方:

  • input元素的内容是通过value属性控制的,你用innerHTML赋值完全无效
  • 没有把年份和生成的4位随机数拼接起来,还是单独赋值了随机数
  • 部分代码在DOM元素加载完成前执行,会导致无法找到目标元素

直接修改代码如下,就能实现年份+4位随机数的效果:

<label class="control-label col-sm-4" for="refno">REF nos :</label>
<div class="col-sm-4">
  <script type="text/javascript">
    window.onload = function () {
        const now = new Date();
        let randomNum = '';
        randomNum += Math.round(Math.random() * 9);
        randomNum += Math.round(Math.random() * 9);
        randomNum += now.getTime().toString().slice(-2);
        // 获取当前年份并拼接成完整编号
        const fullRefNo = now.getFullYear() + randomNum;
        // 给input赋值
        document.getElementById("refno").value = fullRefNo;
    }
  </script>
  <p class="form-control-static" style="margin-top: -6px;">
      <input type="text" class="form-control" id="refno" name="refno" value="<?php echo $refno; ?>" disabled>
  </p>
</div>
<div class="col-sm-10"></div>

关键修改说明:

  • 把所有DOM操作放在window.onload函数内,确保页面元素加载完成后再执行,避免找不到元素的问题
  • 直接用now.getFullYear()获取当前年份,和生成的4位randomNum拼接成完整编号
  • 只保留对input的value属性赋值,移除无效的innerHTML代码

内容的提问来源于stack exchange,提问作者Travis Sloap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:50:10