我想做一个小游戏,但我没有很多经验。另外我知道这可能绝对不是最好的方法,所以如果有人为初学者提供了很棒的东西
<a id="key">There is a key on the floor</a>
<button onclick="keylol()">Pick it up</button>
<a id="door">You see a locked door</a>
<button onclick="doortext()">Try to open the door</button>
<script>
var key = 1
function keylol() {
document.getElementById("key").innerHTML = "You picked up the key";
var key = 2;
}
function doortext() {
if (key = 1) {
document.getElementById("door").innerHTML = "You cannot open a locked door";
} else {
document.getElementById("door").innerHTML = "You opened the door hooray";
}
}
</script>
答案 0 :(得分:1)
您需要使用===
而不是=
:
if (key === 1) {
...
}
答案 1 :(得分:0)
你犯了两个错误:
第一个是您在key
函数的范围内重新声明了一个名为keylol
的新变量,因此值2
未分配给名为的外部变量key
。
第二个是您重新声明key
变量,而不是在if
子句中进行比较。
将var key = 2
更改为key = 2
,将if(key = 1)
更改为if(key === 1)
:
var key = 1
function keylol() {
document.getElementById("key").innerHTML = "You picked up the key";
key = 2;
}
function doortext() {
if (key === 1) {
document.getElementById("door").innerHTML = "You cannot open a locked door";
} else {
document.getElementById("door").innerHTML = "You opened the door hooray";
}
}
<a id="key">There is a key on the floor</a>
<button onclick="keylol()">Pick it up</button>
<a id="door">You see a locked door</a>
<button onclick="doortext()">Try to open the door</button>
答案 2 :(得分:0)
<a id="key">There is a key on the floor</a>
<button onclick="keylol()">Pick it up</button>
<a id="door">You see a locked door</a>
<button onclick="doortext()">Try to open the door</button>
<script>
var key = 1
function keylol() {
document.getElementById("key").innerHTML = "You picked up the key";
key = 2;
}
function doortext() {
if (key == 1) {
document.getElementById("door").innerHTML = "You cannot open a locked door";
} else {
document.getElementById("door").innerHTML = "You opened the door hooray";
}
}
</script>