如何验证文本框中的文本以JavaScript结尾的问号?

时间:2017-09-23 03:14:41

标签: javascript jquery

我正在制作一个神奇的8球网页。用户在文本框中输入问题,单击按钮,将生成并显示随机响应。我有两个规定:如果连续两次询问同一个问题(已完成),我必须抛出警告框;如果问题没有以问号结尾(我在那里),我必须抛出警告框。这是我的代码:

$(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>

1 个答案:

答案 0 :(得分:1)

您错过了对$()的来电。您忘记使用jQuery查找"input[type=text]",而是在此文字字符串上调用.substr"input[type=text]"肯定不会以问号结束。

- 评论 -

不知何故,以上内容尚不清楚,因此我将包含更多细节。在这行代码中:

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

您正在测试字符串"input[type=text]"是否以问号结尾。那永远不会成真。但是,如果您要改变它:

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

您现在正在测试问号字段的值是否以问号结尾,可能在某些时候为真。