首先感謝你今后的幫助!
我正在創建一個通知腳本,修改標題標簽以使(1)出現。 我正在從網站更新的notify_count變數中提取警報的數量。
我所面臨的情況是:
1.標簽中出現了(1),但每次執行newUpdate間隔時都會重復出現。
例如。(1)我的網站,然后(1)(1)我的網站,等等。
- 如果notify_count的值增加,changeTitle函式不會更新numb,同樣的數字會出現在標簽中。
ex: notify_count = 1 -> (1) my site -> notify_count = 2 -> (1) my site
。var numb = notify_count.toString()。
function changeTitle() {
var newTitle = '(' numb ') ' document.title。
document.title = newTitle; }
function newUpdate() {
var update = setInterval(changeTitle, 2000)。
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你需要檢查標題是否已經以(notify_count)開始。如果是的話,你必須替換掉它,而不是在開頭再加上計數。
function changeTitle() {
let prefix = `(${notify_count})`;
if (document.title.match(/^(d ))/) {
document.title = document。 title.replace(/^(d ))/, prefix)。
} else {
document. title = `${prefix} ${document.title} `;
}
}
}
function newUpdate() {
var update = setInterval(changeTitle, 2000)。
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
另一個選擇是在頁面加載時將原始標題保存在另一個變數中。
。let original_title = document.title。
function changeTitle() {
document.title = `(${notify_count}) ${original_title}`;
}
function newUpdate() {
var update = setInterval(changeTitle, 2000)。
}
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你正在得到一個重復的標題,例如:(1) (1) my site
因為這個;
var newTitle = '('/span> numb ') ' document. title。
document.title = newTitle;
你正在將document.title設定為newTitle的值,但你在定義newTitle時使用了現有的document.title值。本質上,這一行是將"(num) "附加到document.title中,一次又一次。
第一次通過 document.title 是 "我的網站",在你附加"(num) "之前。 然后下一次通過 document.title 是 "(1) My Site",然后它被用來定義 newTitle 為 "(1) (1) My Site"。
為了糾正這一點,你可以在changeTitle()中使用一個RegEx,只用String.Replace()替換document.title的"(num) "部分,或者你可以在頂部定義一個新的var來保存原始的document.title并使用這個var作為基礎來建立你的newTitle
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/329646.html
標籤:
