我刚刚进入编程世界,也许我通过快速要求跳了一下,但我从一本书中读到的东西并不理解。为什么我需要为元素密码框创建一个变量,该变量不会保存输入内容的值。 〜对不起:c
function checkPassword() {
var password = document.getElementById("passwordBox");
var passwordGuessed = password.value;
if(passwordGuessed == "Ernest300") {
return true;
}
alert("I'm sorry, your login credentials were incorrect buddy!");
return false;
}
document.getElementById("passwordBox")
返回一个HTML元素对象,其中包含的方法不仅仅是键入输入的值。如果你愿意的话,你可以只做一个这样的变量赋值:var passwordGuessed = document.getElementById("passwordBox").value;
但是大多数人会同意两行更具可读性,而且你可能想要从元素对象中检查其他东西(无论是否在它上面找到等等)在访问该值之前。
该变量不包含密码框中键入的值,但保存对密码框HTML元素本身的引用。您可以通过访问元素的value
属性来获取密码框中输入内容的值。
这里的变量使代码更容易阅读,但您并不真正需要它们。整个代码段可以重写为:
function checkPassword() {
if(document.getElementById("passwordBox").value == "Ernest300") {
return true;
}
alert("I'm sorry, your login credentials were incorrect buddy!");
return false;
}
除非您以后需要,否则无需创建单独的var。例如:
function checkPassword() {
var password = document.getElementById("passwordBox"); // gets the HTML object
var passwordGuessed = password.value; // gets the value of it
if(passwordGuessed == "Ernest300") {
return true;
}
alert("I'm sorry, your login credentials were incorrect buddy!");
password .focus(); // reuse the var
}
VS
function checkPassword() {
var password = document.getElementById("passwordBox").value;
if (password == "Ernest300") {
return true;
}
alert("I'm sorry, your login credentials were incorrect buddy!");
return false;
}
甚至更短 - 但是如果你想测试有效性,使用var总是谨慎的:
function checkPassword() {
if(document.getElementById("passwordBox").value == "Ernest300") {
return true;
}
alert("I'm sorry, your login credentials were incorrect buddy!");
return false;
}