[英]Update Page Title With Update of Span Tag Value using Javascript
I have a span tag with id='title' and this value changes after sometime. 我有一个id ='title'的span标记,此值在一段时间后会更改。 I want to update the page title with this value when it updates. 我要在更新时用此值更新页面标题。
eg <span id='title'>Title</span>
-- This is current title 例如<span id='title'>Title</span>
-这是当前标题
when after some time it is updated by another script to 一段时间后,它被另一个脚本更新为
<span id='title'>New title</span>
I want to update the title of page to "New title" whenever it changes and no matter how many times it changes. 无论何时更改,无论页面更改多少次,我都希望将页面标题更新为“新标题”。
Right now I have to call function every 1 second to update the page title. 现在,我必须每1秒钟调用一次函数来更新页面标题。 Which keeps blinking the page title. 页面标题一直闪烁。 So I want to monitor the change and whenever the value changes I want that value to be the title of page. 因此,我想监视更改,每当值更改时,我都希望该值成为页面的标题。
This discussion seems to be looking at the same issue - just instead of a span they are monitoring a div.I know you're looking to do this with pure JavaScript but I think the thread is still good to review. 这次讨论似乎是针对同一问题-他们不是在监视span而是跨度,我知道您正在使用纯JavaScript进行此操作,但我认为该线程仍然值得审查。
Jquery Event : Detect changes to the html/text of a div jQuery事件:检测对div的html / text的更改
Yes. 是。 You can achieve it by 您可以通过实现
Mutation Observer 变异观察者
I answered your question based on your jsfiddle link in comment I have used MutationObserver to achieve what you want. 我在评论中根据您的jsfiddle链接回答了您的问题,我已经使用MutationObserver实现了您想要的。
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver ||
window.MozMutationObserver;
var target = document.querySelector('#demo');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
console.log(mutation.type);
document.getElementById('status').innerHTML='changed';
}
});
});
observer.observe(target, {
attributes: true,
childList: true,
characterData: true
});
I have forked it to this fiddle . 我已经把它分叉到这个小提琴上了 。
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.