2016-04-28 62 views
0

此提示正常工作,直到我更新了其他一些JavaScript。我不知道我是如何搞砸的。該函數在body標籤中聲明以運行'onload'。Uncaught TypeError:無法讀取屬性'toLowerCase'爲空

function funcPrompt() { 
    var answer = prompt("Are you a photographer?", "Yes/No"); 
    answer = answer.toLowerCase(); 

if (answer == "yes") { 
    alert('Excellent! See our links above and below to see more work and find contact info!'); 
} 
else if(answer == "no") { 
    alert('That is okay! See our links above and below to learn more!'); 
} 
else if(answer == null || answer == "") { 
    alert('Please enter an answer.'); 
    funcPrompt(); 
} 
else { 
    alert('Sorry, that answer is not an option'); 
    funcPrompt(); 
} 
} 

現在突然我收到此錯誤,並且不會顯示提示。

回答

2

如果我們點擊取消,及時將返回nullnull一個不能申請toLowerCase(將導致異常!)

所有其它條件前加一個條件answer===nullreturn,以停止執行一個function

function funcPrompt() { 
 
    var answer = prompt("Are you a photographer?", "Yes/No"); 
 
    if (answer === null || answer === "") { 
 
    alert('Please enter an answer.'); 
 
    funcPrompt(); 
 
    return; 
 
    } 
 
    answer = answer.toLowerCase(); 
 
    if (answer == "yes") { 
 
    alert('Excellent! See our links above and below to see more work and find contact info!'); 
 
    } else if (answer == "no") { 
 
    alert('That is okay! See our links above and below to learn more!'); 
 
    } else { 
 
    alert('Sorry, that answer is not an option'); 
 
    funcPrompt(); 
 
    } 
 
} 
 
funcPrompt();

0

在你的情況下,最好使用一個確認,而不是提示

function funcConfirm() { 
 
    var answer = confirm("Are you a photographer?"); 
 

 
    if (answer === true) { 
 
    alert('Excellent! See our links above and below to see more work and find contact info!'); 
 
    } else { 
 
    alert('That is okay! See our links above and below to learn more!'); 
 
    } 
 
} 
 

 
funcConfirm();

相關問題