Javascript 为什么这不会被触发?

Javascript 为什么这不会被触发?,javascript,function,sockets,socket.io,Javascript,Function,Sockets,Socket.io,我在别处调用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){

我在别处调用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
调用之后按顺序执行的函数中

如果您确定事件正在生成,那么它仅在调用
scoreBoard()
函数之前生成。由于您仅在该函数中附加事件侦听器,因此它仅在您运行
scoreBoard()
后才开始侦听
allScores
事件


解决方法是将('allScores',function(data){…})
部分上的
套接字移动到
scoreBoard()函数体的外部。

因为您没有收到
allScores
事件控制台中有任何错误?控制台中没有错误如果我将allScores放在该函数外部,它会正常工作,一旦我把它放入一个函数中,它就不会触发。你永远不应该在页面加载后使用document.write,而document.write与构建字符串不同。当你写下开始标签时,浏览器会关闭它。是的,这似乎是唯一的方法,但当我不想要它的时候,它会得出分数。这就是为什么,但是谢谢你提供的信息!那是另一个问题;)
console.log('inside');