簡體   English   中英

jQuery-確保用戶不會連續兩次在文本輸入中提交相同的值

[英]jQuery - Making sure user doesn't submit same value in text input twice in a row

我正在創建一個魔術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();
    });
});

從單擊處理程序函數的最后一行刪除var ,因為這是在該函數內部創建一個局部變量,並且在兩次單擊處理程序的調用之間均未保留該值。 您要引用在單擊處理程序外部聲明的questionValue變量。

所以改變:

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

...至:

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

編輯:我剛剛注意到您正在獲取ID為submit的元素的值,該元素與單擊處理程序綁定到的元素相同,這似乎不正確。 在兩次點擊之間,按鈕的值不會改變。 您沒有顯示HTML,所以我不確定文本框的ID是什么,但是您應該在if條件和顯示的行中再次檢查該選擇器。

我發現很難解釋我的變化哈哈

   $(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();
        });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM