2016-10-02 8 views
-2

JavaScriptオブジェクトが存在するかどうかを確認するためにHTML入力を使用するにはどうすればよいですか?フォームにpersonと入力すると、それが存在し、ページがリダイレクトされるという警告が表示されます。違うものを入力すると、それが存在しないという警告が表示されます。あなたがやりたいとトライキャッチでそれを置くためにevalを使用することができますJSオブジェクトが存在するかどうかを確認するためにinputを使用する方法

<!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

。しかし、あなたは実際にそのようにするべきではありません。

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

を試しましたが、動作しません。ページを更新するだけです –

関連する問題