我已经制作了一个每3秒更新一次特定div的功能。但我想要做的是我想检测div中的变化。当div类“.dock-container”获取一个新的子div,或者删除了一个子div时,我想重新加载div,而不管子div被调用了什么。如果没有任何改变,没有添加新的子div,就不会发生任何事情。
这就是我现在所拥有的,它每隔3秒自动更新一次div:
jQuery(document).ready(function($) {
function autoRefresh() {
$.ajax({
success: function(data) {
var result = $('<div />').append(data).find('.dock-container').html();
$('.dock-container').html(result);
}
});
}
autoRefresh();
// Refresh at page load and every 3000 milliseconds / 3 seconds
var auto_refresh = setInterval(autoRefresh, 3000);
})
编辑:我尝试使用Mozilla的例子:
jQuery(document).ready(function($) {
// Select the node that will be observed for mutations
var targetNode = document.getElementsByClassName('dock-container');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode[0], config);
})
这是我要检测的div的子项,如果它们被删除或添加:
<div class="dock-container">
<div id="widget-clock-widget-15" class="dock-element widget_widget-clock-widget" style="width:50%"><div class="clock"><div class="clock-time"><span class="clock-hours">test 1</span></div></div></div>
<div id="widget-clock-widget-26" class="dock-element widget_widget-clock-widget" style="width:50%"><div class="clock"><div class="clock-time"><span class="clock-hours">test 2</span></div></div></div>
</div>