首页 > 解决方案 > 我正在编写函数,当在 textInput 中的值写为“giorgi”并且在 passInput 中写为“gio”时,警报欢迎,如果不是,则警报错误

问题描述

let userName = document.getElementById('textInput').value; 
let userPass = document.getElementById('passInput').value; 
function myFunction(){ 
  if(userName === 'giorgi' && userPass === 'gio'){ 
    alert('Welcome'); 
  } else { 
    alert('Wrong'); 
  }
}

标签: javascript

解决方案


您只读取一次输入,此时它们是空的。将输入值分配给变量不会创建连接,它只是分配执行分配时输入中的任何字符串。如果稍后它们中的任何一个发生变化,那根本不会影响另一个。

您希望在用户单击登录按钮时读取输入的值。

function login() {
  // notice we're reading and assigning the input values every time this function runs
  let userName = document.getElementById('userName').value;
  let userPass = document.getElementById('userPass').value;
  if (userName === 'giorgi' && userPass === 'gio') {
    alert('Welcome');
  } else {
    alert('Wrong');
  }
}
<input type=text id=userName placeholder="Enter Username" />
<input type=password id=userPass placeholder="Enter Password" />
<button type=button onclick=login()>Login</button>


推荐阅读