繁体   English   中英

onClick按钮只能工作一次

[英]onClick Button Only Works Once

我有一个按钮,用于检查输入文本以查看它是否是正确的密码。 问题是该按钮只能工作一次,当您多次单击时,它不会一遍又一遍地运行该功能。

我的代码:

<html>

<head>
  <title>Password</title>
  <script>
  function passcheck() {
    var attempts = 5;
    var q = document.getElementById('txt').value;
    if (q == "12345") {
      document.getElementById("result").innerHTML = "You're In!";
    } else {
      attempts--;
      document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!";
    }
  }
  </script>
</head>

<body>
  <font face="Verdana" size="5"><b>Enter Your Password:</b></font>
  <br/><br/>
  <input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25">
  <button type="button" onclick="passcheck()">Submit!</button>
  <p id="result"></p>

</body>

</html>

它被多次调用,但您没有看到更改,因为在函数内部定义了attempts 这意味着每次运行该功能时, attempts都会重置为5 要解决此问题,请将attempts语句移到函数外部

 var attempts = 5; // Moved to here so we don't reset the value function passcheck() { var q = document.getElementById('txt').value; if (q == "12345") { document.getElementById("result").innerHTML = "You're In!"; } else { attempts--; document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!"; } } 
 <font face="Verdana" size="5"><b>Enter Your Password:</b></font> <br/> <br/> <input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25"> <button type="button" onclick="passcheck()">Submit!</button> <p id="result"></p> 

您正在初始化“尝试”的值,并在每次调用该函数时递减它。 因此,似乎该函数只被调用一次。

将变量的减速度移到函数外部。 就像是

var attempts = 5;
function passcheck() {
  //code here ...
}

另一种稍微好一点的方法是使用localStorage或sessionStorage甚至使用cookie。

谢谢,帕拉斯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM