[英]Mutation isn't observing and logging to console
I have the following script that runs on page load. 我有以下脚本在页面加载时运行。 It's meant to observe every td
element on the page and check if it changes. 旨在观察页面上的每个td
元素,并检查其是否更改。
I was just logging the mutation to console to see my next steps, as I want to see what values change in each td
element (the div refreshes every 15 seconds that houses the table). 我只是想将突变记录到控制台中以查看下一步,因为我想查看每个td
元素中的值发生了什么变化(div会在容纳表的每15秒刷新一次)。
Here's what I've got so far: 到目前为止,这是我得到的:
jQuery(document).ready(function( $ ) {
/** Change URL */
setInterval(function() {
$.ajax({
url: 'http://localhost:8888/profitmanager/wp-content/plugins/football-stats/update.php'
}).done(function(){
$('.fbs_results').load(
location.href+" .fbs_results>*", function(){
var hidden = [];
$.each(JSON.parse(localStorage.getItem("table_state")), function(index, value) {
if(value == 'hidden'){
$('tr[data-index="'+index+'"]').hide();
}
});
// console.log(hidden);
$('tr').each(function(index){
});
}
);
});
}, 15000);
const config = {
characterData: true,
characterDataOldValue: true,
childList: true,
subtree: true
};
function tdChanges(mutations) {
mutations.forEach((mutation) => {
console.log(mutation);
// if (mutation.addedNodes.value) {
// console.log();
// }
});
}
const tds = document.querySelectorAll('td');
Array.from(tds).forEach(function(td) {
const observer = new MutationObserver(tdChanges);
observer.observe(td, config);
});
});
But it doesn't work, nothing logs. 但这不起作用,什么也没有记录。 Weird. 奇怪的。
Can anyone fix my code? 谁能修复我的代码?
TIA TIA
querySelector()
returns only a single Element. querySelector()
仅返回单个Element。 To look at all of them you need to use querySelectorAll()
then loop over the result: 要查看所有它们,您需要使用querySelectorAll()
然后遍历结果:
const tds = document.querySelectorAll('td');
Array.from(tds).forEach(function(td) {
const observer = new MutationObserver(tdChanges);
observer.observe(td, config);
});
Here's a working example in a jsFiddle , as the SO snippet editor is sandboxed and has issues running MutationObservers. 这是jsFiddle中的一个有效示例,因为SO代码段编辑器已沙盒化,并且在运行MutationObservers时遇到问题。
One thing to note here is that MutationObservers are not fast, and if you have a lot of td
elements in your page you may see a performance hit. 这里要注意的一件事是MutationObservers并不快,如果页面中有很多td
元素,您可能会发现性能下降。 You may be better served by placing a single MutationObserver on the parent table
and letting the event bubble up, like this . 您可以通过将父单一MutationObserver得到更好的服务table
,并让事件冒泡,像这样 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.