Javascript忽略了部分代码,除非我在其前面加上“警告”

我有这个Javascript。 它适用于sockets.io和服务器端Node.js. 在这里,它从服务器获取一组数据并将其显示在屏幕上。

socket.on('score', function(score) { //"score" is an array of things to be displayed on the client $('#scoreb').html(score[0]); $('#scoreb_total').html(score[2]); $('#scorer').html(score[1]); $('#scorer_total').html(score[3]); if(score[5] != "N"){ //find this seat's chair on this client's screen var ch = findChair(score[4]); $('#player'+ch+'_trump').html("Victory!"); } }); 

score类似于[40, 0, 40, 0, 3, "H"] console.log [40, 0, 40, 0, 3, "H"] (使用console.log确认它的格式正确)。

findChair一些计算并返回1到4之间的数字。如果我在调用函数后放入console.log(ch) ,我得到1 (正确)。

if条件之前的代码工作正常。

现在是奇怪的部分。 我的HTML中有这个:

 

因此,在ch初始化之后,相应的div (在本例中为player1_trump )应填充单词Victory! 。 但这不会发生! Weirder仍然,而不是console.log我在这里使用alert

 var ch = findChair(score[4]); alert(ch); $('#player'+ch+'_trump').html("Victory!"); 

当我在警告提示中单击“确定”时,在player1_trump正确显示胜利player1_trump ! 那么这里发生了什么? 这里没有异步,这是普通的客户端Javascript,并且在findChair函数运行后ch显然是正确的。 那么为什么它只在我在一行和另一行之间发出警报时才起作用?

编辑(这是function):

 function findChair(s){ var ch = -1; $.each(chairs, function (chair, seat) { if(s == seat) ch = chair; else $('#player'+chair+'_trump').html(''); }); return ch; } 

编辑2:

如果我替换$('#player'+ch+'_trump').html("Victory!"); with document.getElementById('#player'+ch+'_trump').innerHTML="Victory!" 我得到一个错误,说TypeError: document.getElementById(...) is null 。 但是,如果我在发生任何此类事件之前查看源代码(这一切都发生在单击按钮时,而不是在页面加载时),则存在目标div。

使用$('#player'+ch+'_trump').delay(200).html("Victory!"); 也不起作用,不管我把它拖延多久。 所以这不仅仅是时间问题。

使用.text而不是.html也不起作用。

我自己找到了答案。

对于我的问题的评论是正确的,假设它是socket.io的异步性质的问题。

函数findChair清空了player_trump divs,除了一个。 问题是,除了score套接字侦听器之外,还有另一个套接字侦听器也经常同时运行该函数。 解决方案只是采取将div排空的函数,以便其他函数调用不会清空它们:

 var ch = findChair(score[4]); $('.player_trump').html(''); $('#player'+ch+'_trump').html("Victory!"); function findChair(s){ var ch = -1; $.each(chairs, function (chair, seat) { if(s == seat) ch = chair; }); return ch; }