jQuery - 确保用户连续两次在文本输入中提交相同的值

时间:2017-03-12 04:28:10

标签: javascript jquery html5

我正在创建一个魔术8球应用,用户在输入框中输入问题。他们按下提交按钮,答案将替换标题中的默认html文本。如果连续两次询问相同的问题,我想显示警告消息而不是给出新的答案。我是jQuery的新手,我无法弄清楚如何存储输入的最后一个值。我真的很感激一些意见。提前谢谢。

$(document).ready(function(){
    var questionValue;
    $("#submit").click(function() {
        //Make sure user doesn't ask same question twice in a row
        if (questionValue != $("#submit").val()) {

            //List of possible responses
            var response = ["Ask again later…", "Yes", "No", "It appears so", "Reply is hazy, please try again", "Yes, definitely", "What is it you really want to know?", "Outlook is good", "My sources say no", "Signs point to yes", "Don't count on it", "Cannot predict now", "As I see it, yes", "Better not tell you now", "Concentrate and ask again"];

            //generate a random number between 0-14
            var randomNumber = Math.floor(Math.random() * 15);

            //Present random answer
            $("#eightBallAnswer").text(response[randomNumber]);
        }
        else {
            alert("Ask a different question");
        }
        var questionValue = $("#submit").val();
    });
});

2 个答案:

答案 0 :(得分:2)

从单击处理程序函数的最后一行中删除var,因为这是在该函数内创建局部变量,并且在对单击处理程序的调用之间不保留该值。您希望引用在单击处理程序外声明的questionValue变量。

所以改变:

var questionValue = $("#submit").val();

...为:

questionValue = $("#submit").val();

编辑:我刚刚注意到你获得了一个id为submit的元素的值,这个元素与click处理程序绑定的元素相同,这似乎不正确。按钮的值在点击之间不会改变。你没有显示HTML,所以我不确定文本框的ID是什么,但你应该在if条件和我显示的行上仔细检查那个选择器。

答案 1 :(得分:0)

我发现很难解释我的变化哈哈

   $(document).ready(function(){
        var prevquestionValue=$("#input").val();
        $("#submit").click(function() {
            //Make sure user doesn't ask same question twice in a row
            if (prevquestionValue!= $("#input").val()) {

                //List of possible responses
                var response = ["Ask again later…", "Yes", "No", "It appears so", "Reply is hazy, please try again", "Yes, definitely", "What is it you really want to know?", "Outlook is good", "My sources say no", "Signs point to yes", "Don't count on it", "Cannot predict now", "As I see it, yes", "Better not tell you now", "Concentrate and ask again"];

                //generate a random number between 0-14
                var randomNumber = Math.floor(Math.random() * 15);

                //Present random answer
                $("#eightBallAnswer").text(response[randomNumber]);
            }
            else {
                alert("Ask a different question");
            }
            prevquestionValue = $("#input").val();
        });
    });