我有一个div,其内容一直在变化,例如ajax requests
,jquery functions
,blur
等。>
有没有一种方法可以随时检测div上的任何更改?
我不想使用任何间隔或检查的默认值。
这样的事情会做
$('mydiv').contentchanged() {
alert('changed')
}
我有一个div,它的内容一直在变化,无论是ajax请求,jquery函数,blur等。我有什么方法可以在任何时间检测到div上的任何更改?我不要...
如果您不想使用计时器并检查innerHTML,则可以尝试此事件
尝试使用MutationObserver:
[通过jQuery或直接通过DOM-API向div中添加一些内容,默认为<html>
<!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// Inspect the array of MutationRecord objects to identify the nature of the change
function mutationObjectCallback(mutationRecordsList) {
console.log("mutationObjectCallback invoked.");
mutationRecordsList.forEach(function(mutationRecord) {
console.log("Type of mutation: " + mutationRecord.type);
if ("attributes" === mutationRecord.type) {
console.log("Old attribute value: " + mutationRecord.oldValue);
}
});
}
// Create an observer object and assign a callback function
var observerObject = new MutationObserver(mutationObjectCallback);
// the target to watch, this could be #yourUniqueDiv
// we use the body to watch for changes
var targetObject = document.body;
// Register the target node to observe and specify which DOM changes to watch
observerObject.observe(targetObject, {
attributes: true,
attributeFilter: ["id", "dir"],
attributeOldValue: true,
childList: true
});
// This will invoke the mutationObjectCallback function (but only after all script in this
// scope has run). For now, it simply queues a MutationRecord object with the change information
targetObject.appendChild(document.createElement('div'));
// Now a second MutationRecord object will be added, this time for an attribute change
targetObject.dir = 'rtl';
</script>
</body>
</html>
函数。您可以做的是重写当前对象的.appendChild()
函数,并在其中实现观察者。现在已经重写了.appendChild()
函数,我们需要从另一个对象借用该函数以能够附加内容。因此,我们调用另一个div的.appendChild()
来最终附加内容。当然,这对于.appendChild()
也很重要。
使用Javascript $("body").on('DOMSubtreeModified', "#selector", function() {
// code here
});
您可以尝试这个
您正在寻找$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {
});
或MutationObserver。开发者世界都没有得到所有人的支持,也没有太过热情地看待它们。
以下代码对我有用。
没有针对此问题的内置解决方案,这是您的设计和编码模式中的问题。
使用changeHtml('#mydiv', '<p>test content</p>');
提供的摘录中的MutationObserver,并改编自Mozilla
您可以将div的旧innerHTML存储在变量中。设置间隔以检查旧内容是否与当前内容匹配。如果不是这样,请执行某些操作。