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

如何无需刷新页面,多次提交后检测number类型输入框值并更新样式?

问题解决:年龄检查器无需刷新即可重复生效

你的年龄检查器只能生效一次的原因很明确:输入框的值在页面加载时就被固定了,之后点击按钮不会重新读取最新的输入内容,导致后续修改年龄后程序还是在用第一次的旧值判断。

修改后的代码

HTML部分(无需改动)

<div class="container">
  <form>
    <label for="age">Check your age</label>
    <input type="number" min="5" max="100" id="ageInput" onfocus="this.value=''">
    <input id="inpBtn" type="button" value="Submit">
  </form>
  <div id="underage">
    <p>You need to get older. You're underage.</p>
  </div>
  <div id="ofAge">
    <p>You are good to go.</p>
  </div>
  <div id="tooOld">
    <p>You are too old for this club</p>
  </div>
</div>

JavaScript部分(核心修改)

$(document).ready(function(){
  $("#inpBtn").click(function(){
    // 每次点击按钮时,重新获取输入框的最新值
    let ageInput = $("#ageInput").val();
    // 先重置所有提示文本的颜色,避免旧样式残留
    $("#underage, #ofAge, #tooOld").css("color", "");
    
    console.log(ageInput);
    if(ageInput < 18) {
      $("#underage").css("color", "red");
      console.log("under 18");
    } else if (ageInput >= 18 && ageInput < 80) {
      $("#ofAge").css("color", "green");
      console.log("good to go");
    } else {
      $("#tooOld").css("color", "gray");
      console.log("too old");
    }
  });
});

关键修改点

  1. 移到点击事件内获取值:把获取输入值的代码从全局移到按钮的点击回调里,确保每次点击都读取最新输入内容。
  2. 重置旧样式:每次判断前先清空所有提示文本的颜色,避免之前的颜色影响新的判断结果(比如之前选17让underage变红,之后选20时,underage的红色会保留,重置后就不会有这个问题)。
  3. 改用jQuery获取值:用$("#ageInput").val()替代原生JS的写法,更贴合你正在学习的jQuery语法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:05:31