2016-10-02 43 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

我試過了,但它不起作用,它只是刷新頁面 –