2015-10-26 180 views
1

我想要做的就是讓用戶單擊一個按鈕來生成一個隨機數。它似乎工作,但號碼只在消失前顯示一秒。 這是我的代碼。在JavaScript中生成一個隨機數

<!DOCTYPE html> 

<head> 
</head> 

<body> 

<h3> 
This is a random number generator! 
</h3> 

<form onsubmit= "randomNumber()"> 
<input type="submit" value="Click me!"> 
</form> 

<script> 
function randomNumber() { 
    document.write(Math.floor(Math.random() * 10)); 
} 
</script> 

<p id="number"> 
</p> 
</body> 
</html> 
+2

您需要阻止表單提交,並且[您不應該使用'document.write'](http://stackoverflow.com/q/802854/1048572),因爲它會清除當前頁面。 – Bergi

+1

不要使用document.write http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – epascarello

+0

@epascarello:1s太晚了:-D – Bergi

回答

4

你需要

<form onsubmit="randomNumber(); return false;"> 

防止頁面的新負載和

function randomNumber() { 
    document.getElementById('number').innerHTML = Math.floor(Math.random() * 10); 
} 

設定值。

+0

'innerText'沒有在Firefox中工作,如果你想成爲w3c-DOM兼容的話,可以使用'innerHTML'或'textContent'(後者不支持IE <9)。 – deamentiaemundi

+0

@deamentiaemundi,我改變了。 :) –

+0

比讓我成爲這個社區的忠實會員,並給你一個大拇指,不要等待,錯誤的組,啊,這是一個+1,對不起。 – deamentiaemundi

1

尼娜的回答很好,但你並不需要一個表格。這個怎麼樣,而不是你的形式?

<button onclick="randomNumber()">Click me!</button> 

然後randomNumber功能會去尼娜建議:

function randomNumber() { 
    document.getElementById('number').innerText = Math.floor(Math.random() * 10); 
} 

既然沒有形式,沒有必要爲了防止從形式實際上被髮送。

順便說一下,這將把隨機數字放在p中,id爲「number」,我猜是你想要的。但是,如果您想離開僅包含數字的頁面,請使用document.write而不是document.getElementById ...,如您的原始代碼片段中所示。