JavaScript中的Magic 8球

时间:2015-09-09 05:47:43

标签: javascript html html5 web

我希望创造一种“魔术八球”#34;网站。我想到的This is an example。如何编写代码来模仿这种随机答案效果?

1 个答案:

答案 0 :(得分:4)

当然,您可以从数组中选择随机答案并显示它们。假设您有一个名为answers的数组。您可以随意选择一个:

var answer = answers[Math.floor(Math.random() * answers.length)];

然后,您可以将答案插入名为answerContainer的元素中,例如:

document.getElementById('answerContainer').innerHTML = answer;

这是一个演示:



var answers = [
  'Maybe.', 'Certainly not.', 'I hope so.', 'Not in your wildest dreams.',
  'There is a good chance.', 'Quite likely.', 'I think so.', 'I hope not.',
  'I hope so.', 'Never!', 'Fuhgeddaboudit.', 'Ahaha! Really?!?', 'Pfft.',
  'Sorry, bucko.', 'Hell, yes.', 'Hell to the no.', 'The future is bleak.',
  'The future is uncertain.', 'I would rather not say.', 'Who cares?',
  'Possibly.', 'Never, ever, ever.', 'There is a small chance.', 'Yes!'];

document.getElementById('answerButton').onclick = function () {
var answer = answers[Math.floor(Math.random() * answers.length)];
    document.getElementById('answerContainer').innerHTML = answer;
};

p, input, button {
  font-family: sans-serif;
  font-size: 15px;
}
input {
  width: 200px;
}

<p> How can I help you today? </p>

<input type="text" placeholder="enter a question"></input>

<button id="answerButton"> Answer me </button>

<p id="answerContainer"></p>
&#13;
&#13;
&#13;