我有一个数据库,我在那里存储一个文本,它的持续时间和时间,当它应该出现在网页上。
php的结果如下:
{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:15"},{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:30"},{"text_content":"gdsgdsgds","text_duration":"15","start_time":"2015-10-01 14:00:00"}
我有一个jquery脚本,从数据库中获取数据,并打印在屏幕上:
var results =[];
var cursor = 0;
function myFunction () {
$.getJSON('list2.php', function(json) {
results = json;
cursor = 0;
// Now start printing
printNext();
});
}
function printNext(){
if(cursor == results.length){
// Reset the cursor back to the beginning.
cursor = 0;
}
// Print the key1 in the div.
//$('#mydiv').html(results[cursor].key1);
$('#mydiv').hide('fast', function(){ $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); });
// Set a delay for the current item to stay
// Delay is key2 * 1000 seconds
setTimeout(function(){
printNext();
}, results[cursor].text_duration * 1000);
// Advance the cursor.
cursor++;
}
,现在我想添加一个功能,文本显示在屏幕上只有从数据库中获取的日期,作为start_time
,但我不确定是否有可能只对jquery做,没有任何进一步访问服务器代码。我尝试添加一些if语句,如:
if(results[cursor].start_time == new Date()){
,然后再打印到屏幕上,但是没有成功。你能帮我吗?谢谢!
用JSON.parse
解析json字符串:
var myObj = JSON.parse(results[0]);
和比较你的start_time
:
if (new Date(myObj.start_time) == new Date())
如果你想在特定时间运行你的函数,使用setTimeout:
var diff = new Date(myObj.start_time).getTime() - new Date().getTime();
setTimeout(function() {
$('#mydiv').hide('fast', function() {
$('#mydiv').html(results[cursor].text_content);
$('#mydiv').show('fast');
});
}, diff)
或者您可以使用setInterval
每1000毫秒执行一次函数,并使用clearInterval
停止它:
function check() {
if (new Date(myObj.start_time) == new Date()) {
$('#mydiv').hide('fast', function() {
$('#mydiv').html(results[cursor].text_content);
$('#mydiv').show('fast');
});
clearInterval(myInterval);
}
}
var myInterval = setInterval(check, 1000)