2015-09-25 21 views
0

在下面的代碼中,我想function 2更改text中的文本以完成循環。不幸的是,var rand不會將text更改爲另一個詞。相反,它會一直保持一直。使用Math.random獲取相同的值

var x = 0; 

function function1() { 
    document.getElementById("text").textContent = rand; 
} 

function function2() { 
    if (document.getElementById("text").innerHTML === "Red") { 
     x += 1; 
     document.getElementById("text2").textContent = x; 
     function1(); 
    } 
} 

//I have got the equivalent functions for blue, green and gold as well 
var randomarray = ['Red', 'Blue', 'Green', 'Gold', ]; 
var rand = randomarray[Math.floor(Math.random() * randomarray.length)]; 

有人可以告訴我如何解決這個問題。

+0

我不清楚你在問什麼:句子在語法上沒有多大意義。請重新表達你的問題。 –

+0

那麼,你永遠不會改變'rand'。你設置一次就是這樣。如果你想'rand'改變你必須改變它。 –

+0

如何?菲利克斯國王 – ZAZLEO

回答

0

將rand的聲明移到function1中。這樣,它確實選擇了一個 再次顏色每次FUNCTION1被稱爲

function function1() { 
var rand = randomarray[Math.floor(Math.random() * randomarray.length)]; 
document.getElementById("text").textContent = rand; 
} 

,並註釋掉(或刪除),你有兩種功能之外,它變得無關緊要的聲明。

//var rand = randomarray[Math.floor(Math.random() * randomarray.length)]; 
+0

爲OP添加一些解釋,只是發佈一些代碼不是一個好的答案.. –

+0

我不同意這個工作 – ZAZLEO

+0

@AZAZLEO我沒有說這是行不通的,我只是試圖找到一些高質量的答案。所以...... –