为什么第二个功能不起作用?

时间:2017-10-14 23:08:40

标签: javascript function

我想做一个小游戏,但我没有很多经验。另外我知道这可能绝对不是最好的方法,所以如果有人为初学者提供了很棒的东西

<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>

3 个答案:

答案 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>