我正在构建一个Magic 8 Ball页面,每次我点击页面上的提交按钮时,我的标题#eightBallAnswer中的文本会在一小段时间内变为我的随机答案之一,然后再更改为我的HTML中的原始文本。我已经在多个浏览器中尝试了这个功能。我们将非常感谢您的一些见解。
这是我的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]);
});
});
答案 0 :(得分: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]);
});
});