2017-02-02 70 views
1

我有一個java腳本數組,裏面有大量的元素,點擊一個按鈕我想在屏幕上顯示隨機數組元素,爲此我有使用Math.random函數,但不知道爲什麼它不起作用。 這裏是我的代碼如下。如何在Javascript中使用隨機數組元素onclick

<html> 
 
    <head> 
 
    <title>Demo</title> 
 
    </head> 
 
    <body> 
 
    <button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button> 
 
    <p id="quoteshere" ></p> 
 
    <script> 
 
     var Loadquotes= function(){ 
 
     var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10'); 
 
     var i; 
 

 
     for (i=0;i<quotes.length;i++){ 
 
      var newquotes = quotes[Math.floor(Math.random() * quotes.length)]; 
 
      document.getElementById('quoteshere').value=newquotes; 
 
     } 
 
     }; 
 
    </script> 
 
    </body> 
 
</html>

+0

'quotes.length'會比總項目數多一個。也許試試'quotes.length - 1'? - 另外,'.value'不是一個段落元素的有效屬性,即使它是,for循環也會多次覆蓋該值。 – evolutionxbox

+0

@evolutionxbox試過它..但仍然無法正常工作 –

回答

2

quoteshereP標籤value功能將無法正常工作使用innerTextinnerHTML代替請看下面摘錄

var Loadquotes= function(){ 
 
    debugger; 
 
    var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10'); 
 
    var i; 
 

 
    for (i=0;i<quotes.length;i++){ 
 
    var newquotes = quotes[Math.floor(Math.random() * quotes.length)]; 
 
    document.getElementById('quoteshere').innerText = newquotes; 
 
    } 
 
};
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button> 
 
<p id="quoteshere" ></p>

1

,你可以試試這個

var quotes = Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10'); 
 
var Loadquotes= function(){ 
 
    var newquotes = quotes[Math.floor(Math.random() * quotes.length)]; 
 
    document.getElementById('quoteshere').innerHTML=newquotes; 
 
};
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button> 
 
<p id="quoteshere" ></p>

0

嘗試這個

<html> 
<head> 
    <title>Demo</title> 
</head> 
     <body> 
       <button id="getquotes" value="Quotes" onclick="Loadquotes()"> Quotes </button> 
        <p id="quoteshere" ></p> 
         <script> 
       function Loadquotes(){ 
       var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10'); 
       var newquotes = Math.floor(Math.random() * quotes.length); 
       document.getElementById('quoteshere').innerHTML = quotes[newquotes]; 

       } 
         </script> 
     </body> 

相關問題