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

DOM开发问题:未点击提交按钮,saveCustomer函数自动执行

问题分析与解决方案

嘿,我一眼就揪出你遇到的问题啦!

核心问题

你在给提交按钮绑定点击事件的时候犯了个常见错误:addEventListener的第二个参数应该是函数的引用,但你现在直接写了saveCustomer(ID, customerFirstName, customerLastName, customerPassword)——这会导致代码执行到这一行时,立刻调用saveCustomer函数,而不是等用户点击按钮才触发!

另外还有个小问题:你在打开注册界面的时候就获取了输入框的值,这时候用户还没来得及输入内容,拿到的自然都是空字符串,就算后面点击按钮,用的也是一开始的空值。

修复后的代码

1. 修改registerScreen函数

把获取用户输入的逻辑移到点击事件里,同时修正事件绑定的写法:

function registerScreen() {
  document.getElementById("welcome-container").style.display = "none";
  document.getElementById("registerScreen").style.display = "block";
  
  // 生成并显示随机ID(这里用=代替+=,避免重复叠加ID)
  let randomIDElement = document.getElementById("randomID");
  let customerID = Math.floor((Math.random() * 999) + 100);
  randomIDElement.innerHTML = customerID;

  const submitBtn = document.getElementById("submitInfo");
  
  // 先移除旧的事件监听(避免重复打开注册界面时绑定多次)
  submitBtn.removeEventListener("click", handleSubmit);
  
  // 定义点击回调函数,点击时才执行
  function handleSubmit() {
    // 点击按钮时才获取用户输入的最新值
    let firstName = document.getElementById('firstName').value;
    let lastName = document.getElementById('lastName').value;
    let password = document.getElementById('password').value;
    
    saveCustomer(customerID, firstName, lastName, password);
  }
  
  // 绑定点击事件(传递函数引用,不是直接调用)
  submitBtn.addEventListener("click", handleSubmit);
}

2. 优化saveCustomer函数(加表单验证)

给函数加个简单的非空验证,避免用户提交空表单:

function saveCustomer (ID, customerFirstName, customerLastName, customerPassword) {
  // 先检查必填项是否为空
  if (!customerFirstName.trim() || !customerLastName.trim() || !customerPassword.trim()) {
    alert("请填写完整的注册信息哦!");
    return; // 不执行后续代码
  }

  let customer = {
    id: ID,
    firstname: customerFirstName,
    lastname: customerLastName,
    password: customerPassword,
    cashAmount: 0,
  }

  if (localStorage.getItem("customers") === null) {
    let customers = [];
    customers.push(customer);
    localStorage.setItem("customers", JSON.stringify(customers));
  } else {
    let customers = JSON.parse(localStorage.getItem("customers"));
    customers.push(customer);
    localStorage.setItem("customers", JSON.stringify(customers));
  }
  alert("Registration successful.");
}

为什么这样改?

  • 事件绑定逻辑:用匿名/命名函数作为回调,确保只有用户点击按钮时才会调用saveCustomer,而不是页面加载时自动执行。
  • 输入值时机:在点击按钮时才获取输入框的值,保证拿到的是用户填写后的最新内容。
  • 重复绑定防护:每次打开注册界面时先移除旧的监听,避免多次打开后点击一次按钮触发多次提交。
  • 表单验证:提前拦截空表单提交,提升用户体验。

内容的提问来源于stack exchange,提问作者Özenç B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:30:45