我有一个数据库,我在那里存储一个文本,它的持续时间和它应该出现在网页上的时间.
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"}
Run Code Online (Sandbox Code Playgroud)
我有一个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++;
}
Run Code Online (Sandbox Code Playgroud)
现在我想添加一个功能,只有在从数据库中提取的日期才能在屏幕上显示文本start_time,但是我不确定是否可以仅在jquery上执行,而无需进一步访问服务器代码.我尝试添加一些if语句,如:
if(results[cursor].start_time == new Date()){
Run Code Online (Sandbox Code Playgroud)
就在将它打印在屏幕上之前,但它没有做到这一点.你能帮帮我吗?谢谢!
解析你的json字符串JSON.parse:
var myObj = JSON.parse(results[0]);
Run Code Online (Sandbox Code Playgroud)
并比较你的start_time:
if (new Date(myObj.start_time) == new Date())
Run Code Online (Sandbox Code Playgroud)
如果你想在特定的时间运行你的函数使用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)
Run Code Online (Sandbox Code Playgroud)
或者你可以通过使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |