如何监听title元素的更改? [英] how to listen for changes to the title element?
本文介绍了如何监听title元素的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在javascript中,是否有一种技术可以监听title元素的更改?
In javascript, is there a technique to listen for changes to the title element?
推荐答案
5年后我们终于有了更好的解决方案。使用 MutationObserver !
5 years later we finally have a better solution. Use MutationObserver!
简而言之:
new MutationObserver(function(mutations) {
console.log(mutations[0].target.nodeValue);
}).observe(
document.querySelector('title'),
{ subtree: true, characterData: true }
);
评论:
// select the target node
var target = document.querySelector('title');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
// We need only first event and only new value of the title
console.log(mutations[0].target.nodeValue);
});
// configuration of the observer:
var config = { subtree: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
此外 Mutation Observer拥有令人敬畏的浏览器支持:
这篇关于如何监听title元素的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文