问题
This is just a boiled down example not an actual thing.
Still MutationObserver isn't firing so my assumption on how it works is wrong.
JSFiddle
$(function() {
var editButtonVisibility = function() {
console.log('bam');
}
$('#RiskPostcodeSummary span').on("change", function() {
console.log("pew pew");
});
var observer = new MutationObserver(function(e) {
editButtonVisibility();
});
observer.observe($('#RiskPostcodeSummary span')[0], {
characterData: true
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="RiskPostcodeSummary">
<span></span>
</div>
<input type="button" value="click" onClick="$('#RiskPostcodeSummary span').text('sdfsdf');" />
Why isn't MutationObserver
firing when I change text in <span>
?
回答1:
Adding childList: true
fixes the problem.
From https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver:
childList: Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed.
In your example, you're changing the text node child of the span
element.
$(function() {
var editButtonVisibility = function() {
console.log('bam');
}
$('#RiskPostcodeSummary span').on("change", function() {
console.log("pew pew");
});
var observer = new MutationObserver(function(e) {
editButtonVisibility();
});
observer.observe($('#RiskPostcodeSummary span')[0], {
characterData: true,
childList: true
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="RiskPostcodeSummary">
<span></span>
</div>
<input type="button" value="click" onClick="$('#RiskPostcodeSummary span').text('sdfsdf');" />
来源:https://stackoverflow.com/questions/33521073/mutationobserver-on-span-text-change-does-not-trigger