我在别处调用 scoreBoard() ,它在函数内部运行 console.log,但它不会进一步进入下一个函数?谁能告诉我这是为什么?因为我只想调用此 socket.on 或至少在玩家已登录时绘制表格。
var scoreBoard = function(){
console.log('Gets into here, does not go into the next function');
socket.on('allScores', function(data){
console.log('inside');
var playerScores = data;
// console.log(playerScores);
document.write('<table>');
document.write('<tr> <th>Player</th> <th>Score</th> </tr>');
for(var i = 0; i < playerScores.length; i++)
{
document.write('<tr><td>' + playerScores[i].username + '</td><td>' + playerScores[i].score + '</td></tr>');
}
document.write('</table>');
})
}
这没有运行
console.log('inside');
最佳答案
因为 console.log('inside');
在一个事件监听器中。它不在将在上一个 console.log
调用之后按顺序执行的函数内。
如果您确定正在生成事件,那么它只会在调用 scoreBoard()
函数之前生成。由于您只在该函数内附加事件监听器,它只会在您运行 scoreBoard()
后开始监听 allScores
事件。
解决方案是将 socket.on('allScores', function(data){ ... })
部分移到 scoreBoard()
函数体之外.
关于javascript - 为什么这没有被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749658/