问题描述
请有人帮忙。我正在尝试在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;
}
这篇关于javascript按钮从数组中选择随机项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!