繁体   English   中英

用jQuery更改页面标题,而不增加它

[英]change page title with jquery, without incrementing to it

我正在尝试更新用户所在的页面标题,以添加其当前的通知计数(就像facebook一样)

我有这个:

var current_page_title = $(document).find("title").text();
document.title = '(' + data.title_total + ') ' + current_page_title;

问题是,它一直在这样做:“(12)(12)page title”-每次都添加括号号。

有没有办法始终使用原始标题,而不是已经使用方括号的新标题?

您可以将title的原始值保存在代码块的外部,在此处进行更改,然后将其追加。

var pageTitle;

var current_page_title = document.title
                     //  ^ btw, no need for $(document).find("title").text() here
if ( !pageTitle ) { pageTitle = current_page_title; }
document.title = '(' + data.title_total + ') ' + pageTitle;

document.title = '(' + data.title_total + ')' + document.title.replace(/\\(*\\)/, '');

使用@ serdar.sanri的答案编辑,可首次使用

看这个例子,我使用正则表达式来获取括号中的值。 尝试使用标题。

https://jsfiddle.net/dsgyjs8m/1/

<input type="text" name="title" id="title" value="(12) lorem ipsum" />
<input type="text" name="newTitle" id="newTitle" value="" />

$(function(){
  var value    = $("#title").val();
  var newValue = value.replace(/([\[(])(.+?)([\])])/g, replacer);

    $("#newTitle").val(newValue);
});

function replacer(match, v1, v2, v3, offset, string) {
  return v1 + (1+parseInt(v2)) + v3;
}

每次都重新编写。 不要盲目添加到当前标题。

您可以缓存当前标题并追加。

var title = document.title;

// later
document.title = ... + title;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM