点击可重用功能只需javascript

时间:2017-10-22 13:28:06

标签: javascript

我目前正在学习javascript的第一阶段。我想要实现的是点击掷骰子按钮和骰子以显示1到6之间的数字。我已经有了工作但我在第一次点击后无法让它工作。我已经尝试了函数等循环。我很新javascript抱歉,如果它是一个愚蠢的问题家伙。 :)



<!DOCTYPE html>
<html>
<head>
	<title>Learn Javascript</title>
	<meta charset="utf-8">
	<style type="text/css">
		body {font-family: sans-serif; margin:0; padding:0; background-color:#ddd; }
		#holder {margin:0 auto; width:150px; text-align:center;} 

		#number { margin:0 auto; height:100px; width:100px; background-color: #fff; border-radius: 5px; text-align:center;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			border:1px solid black;
			font-family: arial;
		}

		input {margin:20px; width:75px; font-weight: bold;}
	</style>
</head>
<body>
<h1>Javascript Dice Roll</h1>

<div id="holder">
	<div id="number">
		<p id="diceNumber" style="font-size: 50px;">- -</p>
	</div>

	<input type="button" name="dice role" onclick="rollTheDice()" value="Roll Dice!">

</div>


<script>

	var dice = Math.floor(Math.random() * 6 ) + 1;

function rollTheDice(){

		document.getElementById("diceNumber").innerHTML = dice;
	}



</script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您必须在每次时单击按钮时生成一个随机数字

function rollTheDice(){
     var dice = Math.floor(Math.random() * 6 ) + 1;
     document.getElementById("diceNumber").innerHTML = dice;
}
<h1>Javascript Dice Roll</h1>

<div id="holder">
	<div id="number">
		<p id="diceNumber" style="font-size: 50px;">- -</p>
	</div>

	<input type="button" name="dice role" onclick="rollTheDice()" value="Roll Dice!">

</div>