如何在javascript中创建一个每次都给出(随机)不同答案的按钮
我是javascript新手,所以这似乎是一个非常有用的论坛。 我只知道基本的HTML和CSS 我想制作一个按钮脚本,当你点击它时,每次点击它都会给出不同的答案。我知道如何制作一个基本按钮,使文本出现在屏幕上,但我不知道如何编写脚本,每次都随机给出不同的答案 更具体地说: 我选了20个不同的答案,每个答案在屏幕上显示的百分比相等/不相等如何在javascript中创建一个每次都给出(随机)不同答案的按钮,javascript,html,button,Javascript,Html,Button,我是javascript新手,所以这似乎是一个非常有用的论坛。 我只知道基本的HTML和CSS 我想制作一个按钮脚本,当你点击它时,每次点击它都会给出不同的答案。我知道如何制作一个基本按钮,使文本出现在屏幕上,但我不知道如何编写脚本,每次都随机给出不同的答案 更具体地说: 我选了20个不同的答案,每个答案在屏幕上显示的百分比相等/不相等 谢谢。在JavaScript中,您可以生成0到19之间的随机数 $("#myButton").click(function(){ var index =
谢谢。在JavaScript中,您可以生成0到19之间的随机数
$("#myButton").click(function(){
var index = Math.floor(Math.random()*19);
var randomAnswer = allAnswers[index];
//display answer
});
然后用它来索引一个包含20个项目的数组这样做是为了10个:
一个小的HTML:
<div id="main">
<button id="rnd">Random</button>
</div>
下面是Javascript的一个开始:
var array=["Item1", "Item2", "Item3", "Item4", "Item5"];
var random = array[Math.floor(Math.random() * array.length)];
console.log(random);
因此,我们设置了一个项目的数组
,并在该数组中选择一个随机项目,然后通过console.log
显示它。您需要做的是bind
将其绑定到按钮上
单击,然后将随机
变量附加到div
,span
等
以下是您需要的:
HTML:
<h1>Will be replaced</h1>
<button id="button">Click Me!</button>
$(document).ready(function() {
var array=["Item1", "Item2", "Item3", "Item4", "Item5"];
$('#button').bind('click', function() {
var random = array[Math.floor(Math.random() * array.length)];
$("h1").html(random);
});
});
答案是否存储在数据库或脚本中?问题如何?您需要一个posibles答案数组..Smart和19,因为该函数还可以“生成”0-19超出数组中第一个位置的结果。(+1)谢谢TGH,但我不知道如何执行它。更新:修复了索引计算中的一个错误谢谢,这是一个非常快速和有用的comunity!
$(document).ready(function() {
var array=["Item1", "Item2", "Item3", "Item4", "Item5"];
$('#button').bind('click', function() {
var random = array[Math.floor(Math.random() * array.length)];
$("h1").html(random);
});
});