2015-10-26 182 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 ...,如您的原始代码片段中所示。