我正在做一个神奇的8球,需要显示以下内容:
如果连续两次询问相同的问题,或者问题没有以“?”结尾,请使用提醒功能提供相应的错误消息。
<!DOCTYPE html>
<body style="background-color:black">
<font size=+ 4 color="white">Magic 8 Ball</font>
<script>
<!-- Begin
var answers = new Array(
"Ask again later…",
"Yes",
"No",
"It appears to be 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",
);
function fortune() {
num = Math.round((answers.length - 1) * Math.random());
return answers[num];
}
// End -->
</script>
<form>
<b style="color:white">What would you like to know?</b>
<br>
<br>
<br>
<input type=text name=question size=35>
<input type=button name=ask value="Ask the 8 ball" onClick="if
(this.form.question.value!='') this.form.answer.value = fortune();"><b style="color:white">
<br>The 8 ball says:</b>
<br>
<br>
<input type=text name=answer size=35>
</form>
&#13;
答案 0 :(得分:0)
将上一个问题存储在变量中并在每个回合中进行比较。像下面的东西。更改代码以满足您的需求,但这样您就可以了解。
<!DOCTYPE html>
<body style="background-color:black">
<font size=+ 4 color="white">Magic 8 Ball</font>
<script>
<!-- Begin
var previousQuestion = null;
var answers = new Array(
"Ask again later…",
"Yes",
"No",
"It appears to be 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",
);
//make this function take a string parameter that will be the users submitted question
function fortune(question) {
var validQuestion = true;
//check if the string meets our criteria
if (question === previousQuestion || question.slice(-1) != "?") {
validQuestion = false;
}
//if string is invalid, no need to continue
if (!validQuestion) {
//give user error alert
alert("Ask a new question or include question mark");
//"reset" the answer textbox
return "";
}
//since we know question is valid at this point, store the question for next go-around
previousQuestion = question;
num = Math.round((answers.length - 1) * Math.random());
return answers[num];
}
// End -->
</script>
<form>
<b style="color:white">What would you like to know?</b>
<br>
<br>
<br>
<input type=text name=question size=35>
<input type=button name=ask value="Ask the 8 ball" onClick="if
(this.form.question.value!='') this.form.answer.value = fortune(this.form.question.value);"><b style="color:white">
<br>The 8 ball says:</b>
<br>
<br>
<input type=text name=answer size=35>
</form>