2015-06-21 84 views
0

對於我的網站,我試圖讓一個按鈕,其中每次按下一個按鈕不同的報價出現。我已經做了一個單獨的文件來做到這一點。我不是很有經驗的JavaScript,所以請幫忙。 這是我的HTML:的Javascript隨機短語從列表

<button">Change Quote</button> 
    <p id="test"></p> 

我的目標給每個引用一個數值從一到十所以它的隨機。另外,當我點擊按鈕時,p會改變。謝謝。

編輯:有什麼辦法讓它循環?例如,一旦我得到第一個報價,它可以進入第二個報價?

新的JS:再次

var quotes = [ 
    "I am Bob", 
    "I am smart", 
    "I am independent", 
    "I am bringing change", 
]; 

document.getElementById("changeQuote").addEventListener("click", function() { 
var q = quotes[ Math.floor(Math.random() * quotes.length) ]; 
document.getElementById("test").innerHTML = q; 

感謝。

+0

在哪裏存儲引號?如果你把它們放在你的JS文件的數組這將是微不足道的,在[隨機](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/從陣列中選擇一個數學/隨機)每次點擊一個按鈕。 – nnnnnn

+0

@nnnnnn我不知道如何,也許在一個數組?不確定。 –

+0

1. [創建報價的陣列。](http://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n)2. [添加一個單擊處理](HTTP:/ /stackoverflow.com/questions/6445207/adding-event-listeners-on-elements-javascript)。 3. [從數組中選擇一個隨機元素。](http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array)4. [更新目標元素的內容。]( http://stackoverflow.com/questions/121817/how-do-i-replace-text-inside-a-div-element#answer-121824) – undefined

回答

2

正如我的評論中所述,將引號存儲在數組中,然後添加一個單擊處理程序,從該數組中隨機選擇。

給您的按鈕的ID,所以它可以很容易地從JS選擇:

<button id="changeQuote">Change Quote</button> 

那麼這樣的事情,使用Math.random() method

var quotes = [ 
     "The quick brown fox jumps over the lazy dog.", 
     "Look out! There are llamas!", 
     "No, really, don't get up.", 
     "Whatever", 
     "Etc."  
    ]; 

document.getElementById("changeQuote").addEventListener("click", function() { 
    var q = quotes[ Math.floor(Math.random() * quotes.length) ]; 
    document.getElementById("test").innerHTML = q;  
}); 

演示:http://jsfiddle.net/9pqqmnrs/

進一步閱讀:

0

簡單的方法:

<p id="test"></p> 

    <script> 
     var quotes = ["quote 1", "quote 2", "quote 3", "quote 4", "quote 5"]; 
     var index = Math.floor((Math.random() * quotes.length)); 
     document.getElementById('test').innerHTML = quotes[index]; 

    </script> 

說明:報價存儲爲陣列。數學函數用於根據引用數組長度確定將生成哪個隨機數。另請參閱:http://www.w3schools.com/jsref/jsref_random.asp