添加到ul列表时的Javascript无限循环

时间:2017-01-31 00:30:07

标签: javascript

我正在制作一个蛇游戏,我试图为列表中所有当前的蛇添加一个排行榜。

这是我正在使用的js功能

function UpdateScore(snakes) //Updates the scores
{
    $("LeaderBoardList").empty();

    for (i in snakes) { //For each instance of snake
         var CurrentSnake = snakes[i]; //Make that the current snake
    var CurrentPlayerID = CurrentSnake.PlayerID; //make their id the current ID

    if (CurrentPlayerID == PlayerID) //Current player has special css for displaying score
    {
        var thisPlayerName = "<h4 class='PlayerScore'>Player " + CurrentPlayerID + "</h3>";
    } else //Different class for other players
    {
        var thisPlayerName = "<h4 class='EnemyScore'>Player " + CurrentPlayerID + "</h3>";
    }

    thisPlayerName += "<h4 class = 'Scores'> Kills: " + CurrentSnake.Kills + ' Score: ' + CurrentSnake.Score + '</h4>'

    $('#LeaderBoardList').append(thisPlayerName); //Show a line for each player

}

}

我首先想到的是因为这个函数很快被调用很多次所以我添加了代码来清除列表但是没有帮助

我刚刚和我一起测试了它并且运行了无限循环,图片here

提前致谢

1 个答案:

答案 0 :(得分:1)

更改

thisPlayerName += "<h4 class = 'Scores'> Kills: " + CurrentSnake.Kills + ' Score: ' + CurrentSnake.Score + '</h4>'

thisPlayerName = "<h4 class = 'Scores'> Kills: " + CurrentSnake.Kills + ' Score: ' + CurrentSnake.Score + '</h4>'

(从+ +中删除+)