我正在製作一個神奇的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>
也添加html代碼。 – Dij
查看代碼:'「input [type = text]」' – epascarello
是的,應該說看看輸入文本字段中的內容,然後轉到字符串的末尾。如果那裏沒有問號,請丟出警報框。但即使在那裏有問號時也是如此。我能想到的唯一的事情就是這樣做,因爲輸入框是空的? – nponinski