JavaScript开关转向

时间:2018-10-03 16:21:33

标签: javascript innerhtml

我正在尝试为棋子做一个功能,它告诉轮到谁的人。

JavaScript

function getCurrentPlayerColor(){
// if even number of moves in moves array, it's black's turn, otherwise red's


   return moves.length % 2 === 0 ? "r" : "b";
}

我想在黑转时使用此功能

 document.getElementById("turn").innerHTML = "Blacks Turn";

并且当它变成红色时此功能

document.getElementById("turn").innerHTML = "Reds Turn";

2 个答案:

答案 0 :(得分:0)

在我看来,就像您已经到了一半一样-您具有检查转弯的功能,因此您可以像这样使用它:

if (getCurrentPlayerColor() === "r") {
    document.getElementById("turn").innerHTML = "Red's Turn";
} else {
    document.getElementById("turn").innerHTML = "Black's Turn";
}

答案 1 :(得分:0)

function getCurrentPlayerColor(){
// if even number of moves in moves array, it's black's turn, otherwise red's
   document.getElementById("turn").innerHTML = (moves.length % 2 ? 'Blacks' : 'Reds') + ' Turn'
}    

function getCurrentPlayerColor(){
// if even number of moves in moves array, it's black's turn, otherwise red's
   return moves.length % 2 === 0 ? "r" : "b";
}

document.getElementById("turn").innerHTML = (getCurrentPlayerColor() === 'r' ? 'Reds' : 'Blacks') + ' Turn'

document.getElementById("turn")turn变量相同,因此我们可以用更短的时间做到这一点

turn.innerHTML = (moves.length % 2 ? 'Blacks' : 'Reds') + ' Turn'