2017-03-12 4 views
0

私はMagic 8 Ballページを作成しています。私のページのSubmitボタンをクリックするたびに、#eightBallAnswerのテキストが私のランダムな回答の1つに数秒間変化してから変更されます私のHTMLの元のテキストに戻ります。私は複数のブラウザでこれを試しました。いくつかの洞察は大いに感謝されるだろう。clickイベントでjQueryで要素のテキストを変更します。後で瞬時に変更する

は、ここに私のjQueryのです:のは、フォームが提出し、さわやかなページ:)

使用される原因と

$(document).ready(function(){ 
    $("#submit").click(function() { 

     //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]); 
    }); 
}); 
+1

'

'要素を使用しないでください。フォーム内に送信ボタンがある場合は、フォームを送信するとフォームが送信され、ページがリロードされます。または、イベントハンドラ内からボタンのデフォルト動作をキャンセルすることもできます。 – nnnnnn

+0

ありがとうございました!これもうまくいき、簡単にするためにあなたのソリューションに行ってきました。フォームタグに含まれていない入力でもHTML5の検証がうまくいくことがわかります。驚くばかり! – thenomadicmann

答えて

0

event.preventDefault()

$(document).ready(function(){ 
    $("#submit").click(function(event) { 

     event.preventefault(); 

     //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]); 
    }); 
}); 
+0

これは、@nnnnnnがうまくいけば、HTMLからフォームタグを削除するだけで、ページがリフレッシュされなくなってしまうのです。みんなの初心者を助けてくれてありがとう! – thenomadicmann

+0

@thenomadicmannようこそ –

関連する問題