【发布时间】:2014-01-31 23:55:41
【问题描述】:
我的 Javascript 中有一个 setInterval 调用,用于检查是否有新的用户通知。此时间间隔进行 AJAX 调用并根据响应更新 DOM。此间隔设置为每 10 秒重复一次。
如果有新通知并且在此间隔内,则需要弹出一个小框。在当前代码中,如果有未标记为 seen 的新通知,则此框每 10 秒显示一次,这很烦人。
有没有办法让这个小框在每个通知集中只出现一次?因此,例如有 X 个新通知,并且 10 秒后这个数字没有改变,不要显示这个框。我如何实现这一目标?我被困在这里了。
这就是我的区间代码的样子:
setInterval(function(){
$.get(generate_site_url() + 'user.php?action=get_notifications', function(data) {
response = $.parseJSON(data);
if ('error' in response)
{
return;
}
if (response.notification_array.length == 0)
{
return;
}
$('.user-notification').text(response.notification_count);
$('.no-notes').hide();
var notificationStr = '';
for (var key in response.notification_array)
{
var notification = response.notification_array[key];
var notificationHTML = '<li' + ((notification.notification_seen == false) ? ' style="background: #fffaf1;"' : '') + '>';
notificationHTML += '<a href="' + notification.notification_target + '" id="nid-' + notification.notification_id + '">';
notificationHTML += '<span class="glyphicon glyphicon-' + ((notification.notification_type == 'like') ? 'thumbs-up' : (notification.notification_type == 'dislike') ? 'thumbs-down' : (notification.notification_type == 'favorite') ? 'heart' : 'bell') + '"></span> ';
notificationHTML += notification.notification_message;
notificationHTML += '</a></li>';
notificationStr += notification.notification_message + '<br />';
$('.notifications-dropdown').prepend($(notificationHTML));
}
display_alert(notificationStr, 'danger', 5000, 'bottom'); // This shows the box
});
}, 10000);
【问题讨论】:
-
if (notificationStr.length > 0) display_alert(...);? -
您已经回答了自己的问题...存储“未见”消息的计数并比较每个间隔。如果新计数高于旧计数,则显示消息。
标签: javascript jquery ajax