2017-10-14 33 views
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"; 
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> 

回答

1

您需要使用===而非=

if (key === 1) { 
    ... 
} 
0

你让两个错误:

第一个是,你重新声明一个在keylol功能的范围内命名key新的变量,因此价值2不是屁股与外部变量key对齐。

第二个是,您将重新声明key变量,而不是在if子句中比较它。

变化var key = 2key = 2if(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>

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>

相关问题