我目前正在使用 jquery 编写一个即时聊天框,它将在顶部显示最新的聊天内容(当用户通过发布请求发送数据时刷新) 并将最旧的聊天内容向下推并将其删除。
问题是,如果检索到多个最新聊天记录(例如 2),则会在前面添加两个新的 div,但只会删除一个最旧的 div,而不是两个...我尝试了超时,但也不起作用。 .
下面是我认为存在问题的代码片段。
function showData(currentchatstyle, data, final){
var newchatstyle;
if (currentchatstyle == "chatone") {
newchatstyle = "chattwo";
}
else {
newchatstyle = "chatone";
}
$('div[class^="chat"]:first').before('<div class="' + newchatstyle + '" style="display:none;">' + data + ' </div>');
$('div[class^="chat"]:first').slideDown(500,"swing", function(){
$('div[class^="chat"]').last().fadeOut(500, function() {
$(this).remove();
});
});
return newchatstyle;
}
$('input[name="content"]').keyup(function(key) {
if (key.which==13) {
var author = $('input[name="author"]').val();
var content = $('input[name="content"]').val();
var lastnum = $('postn:first').text();
var chatstyle = $('div[class^="chat"]:first').attr("class");
$.post(
"chatajax.php",
{ "author": author, "content": content, "lastnum": lastnum },
function(data) {
var msg = data.split("|~|");
for (var i = 0; i < msg.length; i++) {
chatstyle = showData(chatstyle, msg[i], true);
}
}
);
}
});
我们将非常感谢您的帮助。
最佳答案
问题是您确实使用 $('div[class^="chat"]').last()
选择当前淡出的 div,因为您没有 <立即删除它们,但在动画回调中。例如,您可以立即删除 chat
类,这样在下次调用 showData
时就不会选择它。
此外,对于类似的 div,您应该只使用一个“聊天”类,而对于斑马风格,则为它们提供独立的类。
var chatstyle = "one";
function showData(data, final){
chatstyle = chatstyle=="one" ? "two" : "one";
var newDiv = $('<div class="chat '+chatstyle+'" style="display:none;">'+data+'</div>');
$('div.chat:first').before(newDiv);
newDiv.slideDown(500, "swing", function(){
$('div.chat:last').removeClass('chat').fadeOut(500, function() {
// ^^^^^^^^^^^^^^^^^^^^
$(this).remove();
});
});
}
function post(data) {
return $.post(
"chatajax.php",
data,
function(data) {
var msg = data.split("|~|");
for (var i = 0; i < msg.length; i++)
showData(msg[i], true); // what's "final"?
}
);
}
$('input[name="content"]').keyup(function(key) {
if (key.which==13)
post({
"author": $('input[name="author"]').val(),
"content": $('input[name="content"]').val(),
"lastnum": $('postn:first').text() // I'm sure this should not be extracted from the DOM
});
});
关于javascript - 为什么会跳过一些 jQuery/javascript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13862429/