使用 if 和 else 语句第一次单击时按钮不起作用

问题描述 投票:0回答:1

我试图让导航在第一次单击按钮时起作用。但由于某种原因,该按钮在第一次单击时不起作用,但在第二次单击时工作正常

function authenticate() {
  let x = document.getElementById('aut').value;
  if (x == 'code') {
    document.getElementById('myButton').onclick = function() {
      window.location.href = 'https://www.google.com';
    };
  } else {
    alert('Please check your password')
  }
  console.log('If this message appears in the console, JavaScript is running.');
}
<div>
  <label for="auth">Password:</label>
  <input type="password" name="auth" id="aut">
  <button id="myButton" onclick="authenticate()">Authenticate</button>
</div>

javascript buttonclick
1个回答
1
投票

您可以在不声明验证功能的情况下尝试此操作:

document.getElementById("myButton").onclick = function () {
  let x = document.getElementById("aut").value;

  if (x == "code") {
    window.location.href = "https://www.google.com";
  } else {
    alert("Please check your password");
  }
  console.log("If this message appears in the console, JavaScript is running.");
};
© www.soinside.com 2019 - 2024. All rights reserved.