2017-09-23 50 views
-2

我正在製作一個神奇的8球網頁。用戶在文本框中輸入一個問題,單擊一個按鈕,將會生成並顯示一個隨機響應。我有兩個規定:如果連續詢問同一問題兩次(完成),我必須發出警告框;如果問題沒有以問號結束,我必須拋出一個警告框(半途)。這裏是我的代碼:如何驗證文本框中的文本以使用JavaScript的問號結尾?

$(document).ready(function() { 
    var responses = []; 
    responses[0] = "Ask again later..."; 
    responses[1] = "Yes"; 
    responses[2] = "No"; 
    responses[3] = "It appears to be so"; 
    responses[4] = "Reply is hazy, please try again"; 
    responses[5] = "Yes, definitely"; 
    responses[6] = "What is it you really want to know?"; 
    responses[7] = "Outlook is good"; 
    responses[8] = "My sources say no"; 
    responses[9] = "Signs point to yes"; 
    responses[10] = "Don't count on it"; 
    responses[11] = "Cannot predict now"; 
    responses[12] = "As I see it, yes"; 
    responses[13] = "Better not tell you now"; 
    responses[14] = "Concentrate and ask again"; 
    var answer; 
    var questionValue;  

    function getRandom(max) { 
    return Math.floor(Math.random() * max); 
    } 

    $("input[type=button]").click(function() { 
    if ("input[type=text]".substr(-1) != "?") { 
     alert("Ask with a question mark at the end"); 
    } else if(questionValue != $("#txtQuestion").val()) { 
     var my_num = getRandom(15); 
     var answer = responses[my_num]; 
     $("#Response").text(answer); 
    } else { 
     alert("Ask a new question"); 
    } 
    questionValue = $("#txtQuestion").val(); 
    }); 
}); 

在我檢查問號之前,一切工作正常。如果我連續兩次詢問同一個問題,它會拋出一個警告框。但是當我試着在最後檢查一個問號時,它只會拋出一個警告框,說要確保以問號結束,即使最後有一個問號。我究竟做錯了什麼?

更新與HTML代碼:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <title>Magic 8 Ball</title> 
    <link rel="stylesheet" href="styles.css"> 
    </head> 
    <body> 
    <div id="wrapper"> 
     <header> 
     <h1>Magic 8 Ball</h1> 
     </header> 
     <h3>What would you like to know?</h3> 
     <input type="text" name="txtQuestion" id="txtQuestion" /> 
     <br /> 
     <input type="button" id="btnAsk" value="Ask the 8 Ball" /> 
     <h3>The 8 Ball says:</h3> 
     <h3 id="Response">Ask the 8 Ball a question...</h3> 
    </div> 
    <script src="scripts/jquery-3.2.1.js"></script> 
    <script src="scripts/my_scripts.js"></script> 
    </body> 
</html> 
+0

也添加html代碼。 – Dij

+0

查看代碼:'「input [type = text]」' – epascarello

+0

是的,應該說看看輸入文本字段中的內容,然後轉到字符串的末尾。如果那裏沒有問號,請丟出警報框。但即使在那裏有問號時也是如此。我能想到的唯一的事情就是這樣做,因爲輸入框是空的? – nponinski

回答

1

你缺少$()通話。您已經忘記使用jQuery來定位"input[type=text]",而是在文字字符串上調用.substr"input[type=text]"肯定不會以問號結束。

- 您的意見 -

不知何故,上面是不明確的,所以我會包括更多的細節。在這行代碼中:

if ("input[type=text]".substr(-1) != "?") { 

您正在測試字符串"input[type=text]"是否以問號結尾。那就是從來沒有會成爲現實。但是,如果你要改變它,像這樣:

if ($('#txtQuestion').val().substr(-1) != "?") { 

您正在測試你的問題字段的值是否帶有問號,在某些時候它可能真正結束。

+1

我想我不太明白...我是否創建一個var來容納用戶輸入的內容,然後檢查輸入而不是輸入[type = text]? – nponinski

+0

@nponinski - 是的,這就是它。或者,如果你真的不想要中間值,你可以直接在'$('#txtQuestion')。val()'上操作。但是調用''input [type = text]「。substr(-1)'是_always_將返回'」]「'。 –

+0

我將如何直接做到這一點?我無法得到這個工作 – nponinski