如果声明不起作用,我不知道为什么



这是我用于页面的当前版本

input = toString(document.getElementById("pass").value);
function check() {
if (input == "test") {
location.replace("https://google.com");
console.log("correct");
}
else {
document.getElementById("pass").value = "";
alert("Incorrect Password");
console.log("incorrect");
}
}

我在没有toString()函数的情况下尝试了它,但它仍然不起作用。

这里还有链接到它的html:

<div class="main">
<input class="password" id="pass" type="text" placeholder="Enter Your Class">
<button class="password" onclick="check()">Join</button>
</div>

默认情况下,输入值为字符串,不需要转换它们。您应该获取函数内部的输入值。我还建议您避免使用内联事件处理程序:

document.querySelector('button.password').addEventListener('click', check);
function check() {
var input = document.getElementById("pass").value;
if (input == "test") {
location.replace("https://google.com");
console.log("correct");
}
else {
document.getElementById("pass").value = "";
alert("Incorrect Password");
console.log("incorrect");
}
}
<div class="main">
<input class="password" id="pass" type="text" placeholder="Enter Your Class">
<button class="password">Join</button>
</div>

问题是在程序开始时获取文本框的值。document.getElementById("pass").value此代码从一开始就运行,计算结果为""

要解决此问题:

  • input = document.getElementById("pass")替换input = toString(document.getElementById("pass").value);

  • 当比较值时,执行if (input.value == "test")(而不是if (input == "test")(。

相关内容

最新更新