我有这个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
确认其格式正确)。
findChair
执行一些计算并返回1到4之间的数字。如果在调用函数后放置console.log(ch)
,我会得到1
(正确)。
if
条件之前的代码工作正常。
现在是奇怪的部分。我的HTML中有这个:
<div id="player1_trump"></div>
<div id="player2_trump"></div>
<div id="player3_trump"></div>
<div id="player4_trump"></div>
因此,在ch
初始化后,相应的div
(在这种情况下为player1_trump
)应填充单词Victory!
。但这不会发生! Weirder仍然是,而不是console.log
我在这里使用alert
:
var ch = findChair(score[4]);
alert(ch);
$('#player'+ch+'_trump').html("Victory!");
当我在警告提示中点击“确定”时,player1_trump
中会正确显示胜利这个词!那么这里发生了什么?这里没有异步,这是普通的客户端Javascript,ch
函数运行后findChair
显然是正确的。那么为什么它只在我在一行和另一行之间发出警报时才起作用?
编辑(这是函数):
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!");
替换为document.getElementById('#player'+ch+'_trump').innerHTML="Victory!"
,我会收到错误TypeError: document.getElementById(...) is null
。但是,如果我在发生任何此类事件之前查看源代码(这一切都发生在单击按钮时,而不是在页面加载时),则会出现目标div。
使用$('#player'+ch+'_trump').delay(200).html("Victory!");
也不起作用,无论我放入多长时间。所以这不仅仅是时间问题。
使用.text
代替.html
也不起作用。
答案 0 :(得分:0)
我自己找到了答案。
对于我的问题的评论是正确的,假设它是socket.io的异步性质的问题。
函数findChair
正在清空player_trump
div,除了一个。问题是,除了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;
}