javascript按钮从数组中选择随机项 [英] javascript button to pick random item from array

查看:104
本文介绍了javascript按钮从数组中选择随机项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人帮忙。我正在尝试在javascript中创建一个基本按钮,当单击时从我的数组中随机选择一个值并将其显示在屏幕上,每次单击该按钮时它应该从数组中选择一个新项目。我知道如何编写数组

Please can someone help. I am trying to create a basic button in javascript that when clicked picks a value at random from my array and display it on the screen, each time the button is clicked it should pick a new item from the array. I know how to write the array

var myarray = new Array("item1", "item2", "item3");

我只是不知道如何做按钮部分。任何帮助都会很棒。我知道在jQuery中执行此操作可能更容易,但我真的想在解决jQuery问题之前先了解一下javascript(请保持温和我是新来的大声笑)

I just dont know how to do the button part. Any help would be great. I know it may be easier to do this in jQuery, but I really want to get my head round javascript before I tackle jQuery (please be gentle I am new to this lol)

推荐答案

你可以点击按钮来调用一个函数来打印这样的值

You can call a function on button click to print the value like this

<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></p>

JS

function GetValue()
{
    var myarray= new Array("item1","item2","item3");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}

JS小提琴演示

这篇关于javascript按钮从数组中选择随机项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆