我有这段代码,我试图弄清楚为什么我的获胜者if语句不起作用。现在,我只想检查前三个方框是否为“ X”,以及是否要宣布获胜者。
let player1 = "X";
let player2 = "O";
let turn = "X";
let box1 = $('.box1').val();
let box2 = $('.box2').val();
let box3 = $('.box3').val();
let paragraph = $('p');
let everyBox = $('.everyBox');
everyBox.on('click', event => {
if ($(event.currentTarget).attr('disabled')) {
return;
}
if (turn == "X") {
$(event.currentTarget).append(player1);
turn = "O";
} else {
$(event.currentTarget).append(player2);
turn = "X";
}
$(event.currentTarget).attr('disabled', true);
myFunction();
});
function myFunction() {
if (box1 == player1 && box2 == player1 && box3 == player1) {
paragraph.text('player1 wins!').
}
答案 0 :(得分:1)
您的变量box1
,box2
和box3
不是对值的动态引用。它们在分配时很有价值。
您可以通过将这些行移动到myFunction
功能块中来纠正脚本行为:
let player1 = "X";
let player2 = "O";
let turn = "X";
let paragraph = $('p');
let everyBox = $('.everyBox');
everyBox.on('click', event=>{
if ($(event.currentTarget).attr('disabled')) {
return;
}
if(turn=="X"){
$(event.currentTarget).append(player1);
turn="O";
}
else{
$(event.currentTarget).append(player2);
turn="X";
}
$(event.currentTarget).attr('disabled', true);
myFunction();
});
function myFunction(){
let box1 = $('.box1').val();
let box2 = $('.box2').val();
let box3 = $('.box3').val();
if(box1 == player1 && box2 == player1 && box3 == player1){
paragraph.text('player1 wins!').
}
}