问题
I using to a MutationObserver so I can have a div react to changes. When it changes the changes to displayed in the div directly under, however it only runs once. If I type something it to div the input div, only the first character is displayed. I found this on the MDN
"Adding an observer to an element is just like addEventListener, if you observe the element multiple times it does not make a difference. Meaning if you observe an element twice, the observe callback does not fire twice, nor will you have to run disconnect() twice. In other words, once an element is observed, observing it again with the same observer instance will do nothing. However if the callback object is different it will of course add another observer to it."
However I'm not sure how to fix this. I tried making a new observer in the callback of the first observer, in hopes it would create a chain of observers but this hasn't work. How have other people solved this?
<div contenteditable="true" class="input"></div>
<div class="display"></div>
<script>
let input= document.getElementsByClassName("input")[0];
let display= document.getElementsByClassName("display")[0];
let config={attributes:true, childList:true, characterData:true};
let observer= new MutationObserver(function(mutations){
mutations.forEach(function(mutation){
if(mutation.type==="childList"){
display.textContent=input.textContent;
}
});
});
observer.observe(input,config);
</script>
回答1:
You're telling the observer to observe childList and characterData mutations on the input, but the input has no characterData itself. It is the Text nodes inside the input that have characterData mutations.
That leaves the childList. With it, your observer is only triggered when a node is added or removed from the input (when you type the first character, press enter or delete a line).
To fix it, tell the observer to look at the input's descendants by changing the config
to:
{attributes:false, childList:false, subtree: true, characterData:true}
and remove the condition in the observer callback because all mutations will be characterData now. Actually you can just do this:
let observer= new MutationObserver(function(mutations){
display.textContent=input.textContent;
});
since you don't care how many mutations occurred since last time, just the current value.
来源:https://stackoverflow.com/questions/46871258/how-do-i-make-a-mutationobserver-work-more-then-once