我有这样的代码:
function noti() {
document.title = document.title + " 1"
}
setInterval("noti()", 1000)问题在于它的产出:
我的标题1,1,1,1.无限的..。1
有没有可能将其输出为“我的标题1”?
每当数据库中发生更新时,noti()函数都起作用,无论从数据库收集到的长度如何,它都将输出到用户标题栏中。
所以,"My title 1",其中"My title“是用户的名称,"1”是来自数据库的长度。
发布于 2012-05-06 11:28:27
像这样的东西通常都有标记。通常你会看到类似(1) My title的东西。
在这种情况下,这是一件简单的事情:
function noti(num) { // num is the number of notifications
document.title = document.title.replace(/^(?:\(\d+\) )?/,"("+num+") ");
}发布于 2012-05-06 11:26:58
如果只想执行noti一次,则应该使用setTimeout,而不是setInterval。
更新: OK,所以您希望继续执行noti,但是替换后缀而不是每次重新添加它。用正则表达式替换:
document.title = document.title.replace(/(\b\s*\d+)?$/, " " + num);。
发布于 2012-05-06 11:30:24
尝试:
var ttl = document.title; //initalize title
function noti() {
document.title = ttl + " 1";
//if you want to continue setting the title
//(so periodically repeat setting document.title)
//uncomment the following:
//setTimeout(noti, 1000);
}
//use a function reference here. 'noti()' will
//cause the interpreter to do an eval
setTimeout(noti, 1000); 请参阅why you shouldn't use setInterval
https://stackoverflow.com/questions/10470149
复制相似问题