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

登录注册表单问题:点击注册按钮无法将输入值存入数组

问题分析

核心问题是获取输入框值的时机错误:

  • 页面加载完成时你就直接获取了input_username和input_password的value,此时输入框为空,导致newUser和newPass一直是空字符串。
  • 点击注册按钮时,addUser函数只是把预先存好的空值推入数组,自然看不到输入的内容被添加。
修复方案

将获取输入框值的逻辑移到addUser函数内部,确保每次点击注册按钮时,实时获取输入框的最新内容:

修复后的JavaScript代码

// user need to create new username 
// writeing value in username and password inputs and than click registar
// after registar been clicked add inputs values into an array

let btnLogin = document.querySelector('.btn_login')
let btnRegistar = document.querySelector('.btn_registar')

let usernames = [];
let passwords = [];

function addUser(){
   // 每次点击时才获取当前输入框的最新值
   var newUser = document.querySelector('.input_username').value;
   var newPass = document.querySelector('.input_password').value;
   
   usernames.push(newUser);
   passwords.push(newPass); 
   console.log(usernames); // 打印完整数组,查看新增的用户名
   console.log(passwords); // 打印完整数组,查看新增的密码
}

btnRegistar.addEventListener('click', addUser);

额外优化建议

  • 建议将用户名和密码存为对象数组,逻辑更清晰:
let users = [];
function addUser(){
   let newUser = document.querySelector('.input_username').value;
   let newPass = document.querySelector('.input_password').value;
   users.push({username: newUser, password: newPass});
   console.log(users);
}
  • 可添加输入验证,比如判断用户名和密码是否为空,再执行添加操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:03:21