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

JS年份验证代码无响应且判断错误,请求技术排查

JavaScript年份验证代码异常修复

问题描述

代码无报错,但运行不符合预期:输入当前年份(如2023)时,无法输出预期的'Correct',要么无响应,要么仍显示'Incorrect'。

原代码

JavaScript代码

const date = new Date();
const input = document.querySelector('.js-input').value;
const button = document.querySelector('.js-button');
const body = document.querySelector('body');

button.addEventListener('click', yearfunc);

function yearfunc(event) {
  if (input == date.getFullYear()) {
    const div = document.createElement('div');
    button.insertAdjacentElement('afterend', div);
    div.innerText = 'Correct';
  } else {
    const div = document.createElement('div');
    button.insertAdjacentElement('afterend', div);
    div.innerText = 'Incorrect';
  }
  event.preventDefault();
}

HTML代码

<p>What the year is it right now?</p><br><br>
<input type="text" class="js-input">
<button class="js-button">Send</button>

错误原因

  1. 输入值获取时机错误:input变量在页面加载时就获取了输入框的初始空值,后续点击按钮时不会重新获取用户输入的最新内容,导致始终用空值和当前年份比较,自然返回'Incorrect'。
  2. 类型隐式转换隐患:date.getFullYear()返回数字类型,输入框的value是字符串类型,虽然==会做隐式转换,但输入值未更新的情况下,这个转换毫无意义。

修复后的代码

JavaScript代码

const date = new Date();
const button = document.querySelector('.js-button');

button.addEventListener('click', yearfunc);

function yearfunc(event) {
  // 每次点击时获取最新输入值并转为数字
  const inputValue = Number(document.querySelector('.js-input').value);
  // 清除旧提示,避免重复创建元素
  const existingTip = document.querySelector('.year-tip');
  if (existingTip) {
    existingTip.remove();
  }
  
  const div = document.createElement('div');
  div.className = 'year-tip';
  button.insertAdjacentElement('afterend', div);
  
  if (inputValue === date.getFullYear()) {
    div.innerText = 'Correct';
  } else {
    div.innerText = 'Incorrect';
  }
  event.preventDefault();
}

HTML代码

<p>What the year is it right now?</p><br><br>
<input type="text" class="js-input">
<button class="js-button">Send</button>

关键修改点

  • 将输入值获取逻辑移到点击事件内部,确保每次点击都能拿到最新用户输入
  • 使用Number()转换输入类型,用===做严格相等比较,消除类型转换隐患
  • 添加旧提示清除逻辑,避免页面堆积重复提示元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:40:37