2017-10-14 70 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>

相關問題