参考突变观察器 - 网络应用程序接口 |多核 (mozilla.org)和javascript 监听DOM内容改变事件_监听dom的text变化-CSDN博客
// Select the node that will be observed for mutations
const targetNode = document.getElementById("some-id");
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
下面是改变后的:
function wc(){
// 选择将观察突变的节点
//var targetNode = document.getElementById('el-test');
var targetNode = document.querySelector('.xt_video_player_caption');
// 观察者的选项(要观察哪些突变)
var config = { attributes: true, childList: true, subtree: true };
// 当观察到突变时执行的回调函数
var callback = function(mutationsList) {
mutationsList.forEach(function(item,index){
if (item.type == 'childList') {
console.log('有节点发生改变,当前节点的内容是:');
console.log(item.target.innerHTML);
} else if (item.type == 'attributes') {
console.log('修改了'+item.attributeName+'属性');
}
});
};
// 创建一个链接到回调函数的观察者实例
var observer = new MutationObserver(callback);
// 开始观察已配置突变的目标节点
observer.observe(targetNode, config);
// 停止观察
//observer.disconnect();
}
用于记录mooc字幕