gpt4 book ai didi

javascript - 为什么这没有被触发?

转载 作者:行者123 更新时间:2023-11-30 20:45:31 24 4
gpt4 key购买 nike

我在别处调用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com