我正在尝试使用if
语句和输入值创建一个登录系统,我想知道是否有一种方法可以创建类似于数组,变量或对象的东西,我可以将所有密码和用户名和我也可以轻松添加新的用户名。我实际上并没有将它用于网站;这只是一个项目。谢谢。
$(document).ready(function(){
$('.login').click(function(){
var userResult = $('input[name=userInput]').val();
var passResult = $('input[name=passInput]').val();
if(userResult === "CodeAcademy" && passResult === "fun-coding" || userResult === "User_Example" && passResult === "Pass_Example")
{
//Some stuff that will happen
}
});
});
FYI userInput
和passInput
是用户输入用户名和密码的输入框。
答案 0 :(得分:1)
您可以使用查找表Object来避免长链逻辑,数组迭代,额外的字符串引号和慢搜索,以便在一个简单的小数据结构中存储许多登录名和密码:
$(document).ready(function(){
$('.login').click(function(){
var userResult = $('input[name=userInput]').val();
var passResult = $('input[name=passInput]').val();
if({ // username password
CodeAcademy: "fun-coding",
User_Example: "Pass_Example",
"User with space": "sOmeP@ssw0rd",
}[ userResult ] === passResult ){ // user valid and password match?
alert("authenticated"); //Some stuff that will happen
}//end if valid user?
});
});
答案 1 :(得分:0)
您可以使用单独的表单创建登录对象数组,并使用grep
搜索此数组以查看是否存在匹配的用户。这是演示https://jsfiddle.net/f4aqmt4e/
以下是代码和说明:
var myLogins = [];//this might be object that you store the login information
//lets say when a new user registers you keep record of their login information in myLogins
//first create the login information
var myLogin = new Object();
myLogin.Username = "myusername";
myLogin.Password= "12345";
//then add the login information to the login-store array
myLogins.push(myLogin);
$('.login').click(function(){
var userResult = $('input[name=userInput]').val();
var passResult = $('input[name=passInput]').val();
//grep will help you to find a certain element within an array based on a condition
//we will use grep to see if there a matching login info
var loginresult = $.grep(myLogins, function(e){ return e.Username == userResult && e.Password == passResult ; });
if(loginresult.lenght)
{
//login successful
}else {
//login failed
}
});
答案 2 :(得分:0)
$(document).ready(function() {
var vals = [
["CodeAcademy", "User_Example"],
["fun-coding", "Pass_Example"]
];
$(".login").click(function() {
var res = $("._login").toArray().every(function(el, i) {
return i === 0
? $.inArray(el.value, vals[i]) !== -1 // name
: $.inArray(el.value, vals[i]) !== -1 // pass
});
if (res) {
// do stuff
alert("login successful")
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="userInput" type="text" class="_login" />
<input name="passInput" type="text" class="_login" />
<input type="button" class="login" value="login" />