在下面的代码中,通过反复单击2个按钮,observer
仅针对每个观察目标进行第一次更改? (输出显示更改。)
如何在每次更改时触发它?
var cc = 1;
document.querySelector('.button').addEventListener('click', function(e){
var target1 = document.querySelector('.icon-inbox .unread-count');
target1.innerHTML = ' inbox ' + cc++;
});
document.querySelector('.button.nr2').addEventListener('click', function(e){
var target2 = document.querySelector('.icon-achievements .unread-count');
target2.innerHTML = ' reps ' + cc++;
});
(function(title,inbox_counter,reps_counter,inbox_value,reps_value) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type.toLowerCase() == 'attributes' && window.getComputedStyle(mutation.target,null).getPropertyValue("display") == 'none') {
if ((' ' + mutation.target.parentElement.className + ' ').indexOf(' icon-inbox ') > -1) {
inbox_value = '';
} else {
reps_value = '';
}
} else {
if ((' ' + mutation.target.parentElement.className + ' ').indexOf(' icon-inbox ') > -1) {
inbox_value = '(' + mutation.target.textContent + ') ';
} else {
reps_value = '(' + mutation.target.textContent + ') ';
}
}
document.querySelector('.result').innerHTML = inbox_value + reps_value + title;
});
});
observer.observe(inbox_counter, { attributes: true, childList: true, });
observer.observe(reps_counter, { attributes: true, childList: true, });
})(document.title,document.querySelector('.icon-inbox .unread-count'),document.querySelector('.icon-achievements .unread-count'),'','');
.button {
border: 1px solid;
}
div {
height: 24px;
}
<div class="topbar-icon icon-inbox"><span class="unread-count"></span></div>
<div class="topbar-icon icon-achievements"><span class="unread-count"></span></div>
<br><span class="button">BUTTON</span> <span class="button nr2">BUTTON 2</span>
<br><br>Output: <span class="result"></span>
答案 0 :(得分:1)
在选项中,您需要添加两个标记characterdata和subtree
observer.observe(inbox_counter, { attributes: true, childList: true,characterData:true, subtree:true });
observer.observe(reps_counter, { attributes: true, childList: true,characterData:true , subtree:true });