我试图让导航在第一次单击按钮时起作用。但由于某种原因,该按钮在第一次单击时不起作用,但在第二次单击时工作正常
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>
您可以在不声明验证功能的情况下尝试此操作:
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.");
};