我遵循了基于以下内容的教程:http://technotip.com/2208/insert-data-into-mysql-jquery-ajax-php/和http://technotip.com/2298/fetchextract-data-from-database-without-refreshing-webpage-jquery/
这些都很好用。
我的问题是,我如何创建以下过程:
页面加载时,所有现有记录正常显示在 ul 标签中。但是,一旦页面加载完毕,任何新的附加 li 项都会淡入。
function updates() {
$.getJSON("pullsql.php", function(data) {
$("ul").empty();
$.each(data.result, function(){
//$("ul").append("<li>Name: "+this['name']+"</li><li>Age: "+this['age']+"</li><br />");
$('<div></div>').appendTo("ul").hide().append("<li>Name: "+this['name']+"</li><li>Age: "+this['age']+"</li><br />").fadeIn('slow');
});
});
}
到目前为止,我已经尝试将 updates() 函数更改为上面的函数(原始行被注释掉,更改了它下面的行)。
这导致整个 ul 列表每 200 毫秒(更新计时器)淡入淡出一次,但我只需要每个 li 只淡入一次。
提前感谢任何帮助,并很高兴被重定向到适当的教程来帮助我学习,而不仅仅是被灌输代码。
编辑***
我认为到目前为止,以下功能导致了答案的问题:
$(document).ready( function() {
done();
});
function done() {
setTimeout( function() {
updates();
done();
}, 200);
}
我设法使用以下方法让它工作 - 感谢提供 .new 类想法但后来删除了他的答案的人。这通过使用 MySQL 中的自动增量 id 来工作。对于更新而不仅仅是插入的记录,我想我可以在更新时添加一个时间戳,并将 var ulid = 添加到以前的记录时间戳
var ulid = 0;
function updates() {
$.getJSON("pullsql.php", function(data) {
$("ul").empty();
$.each(data.result, function(){
if (ulid >= this['id']){
$("ul").append("<li>Name: "+this['name']+"</li><li>Age: "+this['age']+"</li><br />");
} else {
$("ul li").removeClass("new");
$("ul").append('<li class="new">Name: '+this['name']+'</li><li class="new">Age: '+this['age']+'</li><br />');
$("ul li.new").fadeIn('slow');
ulid = this['id'];
}
});
});
}
你不能在里面有<div>
<ul>
试试这个
function updates() {
$.getJSON("pullsql.php", function(data) {
$("ul").empty();
$.each(data.result, function(){
var newli= "<li>Name: "+this['name']+"</li><li>Age: "+this['age']+"</li><br />";
$(newli).appendTo("ul").hide().fadeIn('slow');
});
});
}
你应该尝试这个:
var newLi = $("<li>Name: "+this['name']+"</li>
<li>Age: "+this['age']+"</li><br />");
newLi.css('display','none').appendTo('ul');
$('ul li:last-child').fadeIn('slow');