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

如何为校园项目网站登录页添加两组用户名密码?

解决多组用户名密码登录的问题

方法1:使用多条件判断(else if)

直接在原有check函数中添加额外条件分支,只要任意一组账号密码匹配就允许登录:

function check(form) {
  const userId = form.userid.value;
  const password = form.pwd.value;

  // 第一组账号密码
  if (userId === "admin" && password === "noahgrocery") {
    return true;
  } 
  // 第二组账号密码
  else if (userId === "student" && password === "campus123") {
    return true;
  } 
  // 所有组都不匹配时提示错误
  else {
    alert("用户名或密码错误");
    return false;
  }
}

方法2:使用数组存储用户信息(更易扩展)

如果后续需要添加更多账号,用数组存储所有合法用户信息会更简洁,维护性更强:

function check(form) {
  const userId = form.userid.value;
  const password = form.pwd.value;

  // 存储所有合法的账号密码对
  const validUsers = [
    { userid: "admin", pwd: "noahgrocery" },
    { userid: "student", pwd: "campus123" },
    // 可继续添加更多用户
    // { userid: "teacher", pwd: "classroom456" }
  ];

  // 检查是否存在匹配的用户
  const isUserValid = validUsers.some(user => 
    user.userid === userId && user.pwd === password
  );

  if (isUserValid) {
    return true;
  } else {
    alert("用户名或密码错误");
    return false;
  }
}

注意事项

  • 前端直接明文存储账号密码非常不安全,仅适合校园演示项目使用。实际生产环境中,必须通过后端接口验证,且密码需要用哈希算法(如bcrypt)加密存储。
  • 可以给input元素添加required属性,强制用户输入内容后再提交表单。

内容的提问来源于stack exchange,提问作者Random Coder 16

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:20:31