私は魔法の8ボールのウェブページを作っています。ユーザーがテキストボックスに質問を入力し、ボタンをクリックすると、ランダムな応答が生成されて表示されます。私は2つの規定を持っています:同じ質問が連続して2回(完了)尋ねられるなら、警告ボックスを投げる必要があります。質問が疑問符で終わっていなければ警告ボックスを投げる必要があります(途中で)。私のコードは以下の通りです:テキストボックス内のテキストを確認するには、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