javascript button to pick random item from array

2020-08-01 06:01发布

问题:

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");

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)

回答1:

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 Fiddle Demo



回答2:

Use Random function of javascript to generate a random number between upper and lower limit of your array. Then use

myarray[Math.round(Math.random() * (myarray.length - 1))]

to access a random value from the array.

You can use this link to see hot to generate a random number between a min and max number. (for your case min will always be 0).



回答3:

http://jsfiddle.net/McKxp/

JS:

var arr = ["foo","bar","baz"];

function getItem(){
    document.getElementById("something").innerHTML = arr[Math.floor(Math.random() * arr.length)];
}

HTML

<div id="something"></div>
<input type="button" onclick="getItem()" value="Click me"/>


回答4:

Try this one: HTML:

<input type="button" click="randomize()" value="Click me" />

JS:

function randomize(){
  var myarray = new Array("item1", "item2", "item3");
  var randomId =  Math.floor((Math.random()*myarray.length));
  var randomItem = myarray[randomid];

  alert(randomItem);
}


回答5:

Here is an example:

http://jsfiddle.net/kUgHg/2/

The steps are:

  1. Create a button element and give it an ID:

    <button id="button1">Show random item</button>
    
  2. Get a reference to the button in your script:

    document.getElementById("button1");
    
  3. Compute a random index in your array based on the array length:

    Math.floor(Math.random() * array.length)
    
  4. Add a click event handler to your button that calls the random computation at step 3 and shows it a way you want:

    button.onclick = function() { … }
    

All in one:

var button = document.getElementById("button1");
var myarray = ["a", "b", "c", "d"];

button.onclick = function() {
    alert(myarray[Math.floor(Math.random() * myarray.length)]);
};