簡體   English   中英

javascript 按鈕從數組中選擇隨機項

[英]javascript button to pick random item from array

請有人幫忙。 我正在嘗試在 javascript 中創建一個基本按鈕,單擊該按鈕時會從我的數組中隨機選擇一個值並將其顯示在屏幕上,每次單擊該按鈕時,它都應從數組中選擇一個新項目。 我知道如何編寫數組

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

我只是不知道如何做按鈕部分。 任何幫助都會很棒。 我知道在 jQuery 中執行此操作可能更容易,但我真的很想在解決 jQuery 之前先了解一下 javascript(請溫柔,我是新手,哈哈)

您可以在單擊按鈕時調用 function 以打印這樣的值

<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 的隨機 function 生成數組上限和下限之間的隨機數。 然后使用

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

訪問數組中的隨機值。

您可以使用鏈接查看熱門以生成介於最小和最大數字之間的隨機數。 (對於您的情況,最小值始終為 0)。

試試這個: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);
}

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"/>

這是一個例子:

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

步驟是:

  1. 創建一個按鈕元素並給它一個 ID:

     <button id="button1">Show random item</button>
  2. 獲取腳本中按鈕的引用:

     document.getElementById("button1");
  3. 根據數組長度計算數組中的隨機索引:

     Math.floor(Math.random() * array.length)
  4. 向您的按鈕添加一個click事件處理程序,該處理程序在第 3 步調用隨機計算並以您想要的方式顯示它:

     button.onclick = function() { … }

一體:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM