如何更新像facebook这样的文档标题并正确删除它?

时间:2013-02-21 18:54:17

标签: javascript jquery facebook

在Facebook收到通知时,文档标题将自动更新

  

(1)Facebook

如何使用javascript进行此操作?

更新 我想知道如何插入(N)并在用户单击指定的div时删除它。

1 个答案:

答案 0 :(得分:5)

有一种简单的方法可以更新 document title

document.title = 'My new title';

以下是一个代码段,当有新通知可用时会更新标题,并在用户点击#foo div时再次更新(删除新通知的数量)。

var title = document.title;
var notifications = 0;
jQuery.post(url, data, function(response) {


    // this regex will test if the document title already has a notification count in it, e.g. (1) My Document
    if (/\([\d]+\)/.test(title)) {
        // we will split the title after the first bracket
        title = title.split(') ');
        // get the first part of the splitted string and save it - this will be the count of the unseen notifications in our document string
        notifications = title[0].substring(1);

        // only proceed when the notification count is difference to our ajax request
        if (notifications == response)
            return;
        // else update the title with the new notification count
        else
            document.title = '(' + sp_response + ') ' + title[1];   
    }   
    // when the current document title does not contain any notification count, just update it
    else {
        document.title = '(' + sp_response + ') ' + title;
    }

});

jQuery('#foo').click(function(event){
    var title = document.title;
    if (/\([\d]+\)/.test(title)) {
        title = title.split(') ');
        document.title = title[1];  
    }
});
相关问题