2016-10-02 62 views
-2

如何使用HTML输入来检查JavaScript对象是否存在?如果我在表单中输入person,它应该会给我一个警报,说它存在并重定向页面。如果我键入不同的东西,它应该得到一个警告,说它不存在。如何使用输入检查JS对象是否存在

<!DOCTYPE html> 
 
<html> 
 

 

 
<input id="auth"> 
 
<button type="button" onclick="authorize()">Submit</button> 
 

 
<script> 
 
function authorize(){ 
 
var auth; 
 

 
auth = document.getElementById("auth"); 
 
auth = window[auth]; 
 

 
\t if (typeof maybeObject !== auth){ 
 
\t \t alert("it works"); 
 
\t } 
 
\t else if (typeof maybeObject === auth){ 
 
\t \t alert("it doesnt work") 
 
\t } 
 

 

 
var person = { 
 
    firstName : "Billy", 
 
    lastName : "Bob", 
 
    age  : 20, 
 
    eyeColor : "purple" 
 
}; 
 

 

 
} 
 
</script> 
 
</html>

+0

什么是'maybeObject'? –

回答

0

您可以使用eval做你想要什么,并把在一个尝试捕捉。但你实际上不应该那样做。

function authorize() { 
 
    var auth; 
 

 
    var person = { 
 
    firstName: "Billy", 
 
    lastName: "Bob", 
 
    age: 20, 
 
    eyeColor: "purple" 
 
    }; 
 

 
    auth = document.getElementById("auth").value; 
 
    try { 
 
    var t = eval(auth); 
 
    alert("exists, hello " + t.firstName); 
 
    } catch (e) { 
 
    alert("doesn't exist"); 
 
    } 
 

 
}
<input id="auth"> 
 
<button type="button" onclick="authorize()">Submit</button>

更好的方式是这样的事情,下面就可以输入第一或姓氏的人,而且如果它存在,你会得到提醒:

function authorize() { 
 
    var auth; 
 

 
    var persons = [{ 
 
    firstName: "Billy", 
 
    lastName: "Bob", 
 
    age: 20, 
 
    eyeColor: "purple" 
 
    }]; 
 

 
    auth = document.getElementById("auth").value; 
 
    if (persons.filter(p => p.firstName == auth || p.lastName == auth).length > 0) { 
 
    alert ("person with that name exists"); 
 
    } else { 
 
    alert("no person with given name exists"); 
 
    } 
 

 
}
<input id="auth"> 
 
<button type="button" onclick="authorize()">Submit</button>

+0

下的“如果它的作品”,我怎样才能让它重定向到不同的页面? –

+0

只需添加'window.location.href ='<你想要去的页面>''@AliKesserwani – baao

+0

我试过了,但它不起作用,它只是刷新页面 –