我正在开展一个项目,根据随机生成的数量,这将给我一个随机的城镇财富。然而,每当我按下“建立乡镇”按钮时,我总是变得“富裕”。如何修复代码以启用所需的结果?
<!DOCTYPE html>
<html>
<body>
<style>
h1 {font-size: 20pt; color: red;}
p {font-size: 17pt; color: blue;}
p2 {font-size: 18pt; color: orange;}
p3 {font-size: 18pt; color: green;}
</style>
<p>This program will create a random town upon the click of a button.</p>
<button onclick="numberdescription()">Establish Township</button>
<br /><br /><br />
<p3 id="random"></p3>
<script>
function numberdescription() {
var num = Math.floor(Math.random() * 3 + 1)
if (num = 1) {
desc = "wealthy";
} else if (num = 2) {
desc = "middle wealth";
} else {
desc = "dirt poor";
}
document.getElementById("random").innerHTML = desc;
}
</script>
</body>
</html>
答案 0 :(得分:2)
=
被视为assignment operator。您需要等于运算符==
,它是comparison operator
function numberdescription() {
var num = Math.floor(Math.random() * 3 + 1)
if (num == 1) {
desc = "wealthy";
} else if (num == 2) {
desc = "middle wealth";
} else {
desc = "dirt poor";
}
document.getElementById("random").innerHTML = desc;
}
答案 1 :(得分:0)
单个=符号赋值,因此您使用此代码
为num赋值1num = 1
将double =替换为double ==。
num == 1