我正在创建一个简单的游戏,其中有两个门,一个包含奖品,另一个不包含(随机生成)。用户可以点击其中任何一个,并在获胜/失败时收到通知。当我运行以下代码时,结果总是“Boo you lose”。我怀疑它与之有关:
if ("door1Selection" === "randomDoor"){
$(document).ready(function() {
let doors = ["door1", "door2"]
function selectDoor() {
const randomDoor = doors[Math.round(Math.random())]
return randomDoor
}
const $door1 = $('.door1')
const $door2 = $('.door2')
$door1.click(function() {
const door1Selection = $door1.attr('class');
if ("door1Selection" === "randomDoor") {
alert("Yay you win")
} else {
alert("Boo you lose")
}
})
$door2.click(function() {
var door2Selection = $door2.attr('class');
if ("door2Selection" === "randomDoor") {
alert("Yay you win")
} else {
alert("Boo you lose")
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="door1">button 1</button>
<button class="door2">button 2</button>
答案 0 :(得分:0)
您的变量不应该用引号括起来。这使它成为一个字符串,所以你要比较永远不会是真的字符串door2Selection === randomDoor
。
你想:
if (door1Selection === randomDoor)
和
if (door2Selection === randomDoor)
您还需要将randomDoor
的声明拉出函数。将其与doors
声明一起使用(并将其设为let
):
let doors = [ /* stuff */ ];
let randomDoor;
function selectDoor() {
randomDoor = doors[Math.round(Math.random())]
return randomDoor;
}
答案 1 :(得分:0)
比较变量时,不应将变量放在引号中。当您将它们放在引号中时,您将比较变量名称本身而不是变量值。
if ("door1Selection" === "randomDoor"){
应该是
if (door1Selection === randomDoor) {
但是,有几个方面可以改进:
进行以下更改会产生以下结果:
$(document).ready(function() {
let doors = ["door1", "door2"]
function selectDoor() {
return doors[Math.round(Math.random())]
}
$('.door').click(function() {
if ($(this).hasClass(selectDoor())) {
alert("Yay you win")
} else {
alert("Boo you lose")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="door door1">Door 1</button>
<button class="door door2">Door 2</button>
答案 2 :(得分:0)
selectDoor()
来获取随机索引。变量randomDoor
范围关闭以选择门锁。
$(document).ready(function() {
let doors = ["door1", "door2"]
function selectDoor() {
const randomDoor = doors[Math.round(Math.random())]
return randomDoor
}
const $door1 = $('.door1')
const $door2 = $('.door2')
$door1.click(function() {
const door1Selection = $door1.attr('class');
if (door1Selection === selectDoor()) {
alert("Yay you win")
} else {
alert("Boo you lose")
}
})
$door2.click(function() {
var door2Selection = $door2.attr('class');
if (door2Selection === selectDoor()) {
alert("Yay you win")
} else {
alert("Boo you lose")
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="door1">button 1</button>
<button class="door2">button 2</button>