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

如何根据用户年龄实现页面跳转?附年龄选择器现有代码参考

基于出生日期的年龄判断跳转实现方案

以下是完整可运行的实现代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Add your Age</title>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css">

  
  <script>
  $( function() {
       $('#datepicker').datepicker({
        changeMonth:true,
        changeYear:true,
        yearRange:"1920:2021" // 可根据需求调整可选年份范围
       });
       $('#datepicker').datepicker('show');

       // 给按钮绑定点击事件
       $('#submitBtn').click(function() {
          const birthDateStr = $('#datepicker').val();
          if (!birthDateStr) {
            alert("请选择出生日期");
            return;
          }
          const birthDate = new Date(birthDateStr);
          const nowDate = new Date();
          // 计算实足年龄
          let age = nowDate.getFullYear() - birthDate.getFullYear();
          const monthDiff = nowDate.getMonth() - birthDate.getMonth();
          // 若今年生日还没过,年龄减1,避免计算误差
          if (monthDiff < 0 || (monthDiff === 0 && nowDate.getDate() < birthDate.getDate())) {
            age--;
          }
          // 年龄区间判断跳转
          if (age < 18) {
            alert("年龄不符合要求");
          } else if (age >=18 && age <=31) {
            // 替换为18-31岁对应的目标跳转地址即可
            window.location.href = "18-31岁目标站点地址";
          } else if (age >=32 && age <=99) {
            // 替换为32-99岁对应的目标跳转地址即可
            window.location.href = "32-99岁目标站点地址";
          }
       })
  });

  </script>
</head>
<body>
 
<p>Date: <input type="text" id="datepicker"></p>
<!-- 给按钮新增id便于绑定事件 -->
<button id="submitBtn" style="background: orange; border: none;padding: 10px 25px;margin-left:40px;">Ok</button>
 
 
</body>
</html>

核心逻辑说明:

  • 新增了出生日期非空校验、年龄合法性校验逻辑,避免异常操作
  • 年龄计算会自动校验当年生日是否已过,不会出现仅按年份算年龄的误差
  • 代码中跳转地址替换为你自己的目标站点地址即可正常使用

内容的提问来源于stack exchange,提问作者dipu barman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:36:06