jQuery 事件:检测对 div 的 html/text 的更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15657686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Event : Detect changes to the html/text of a div
提问by BoqBoq
I have a div which has its content changing all the time , be it ajax requests
, jquery functions
, blur
etc etc.
我有一个 div,它的内容一直在变化ajax requests
,例如jquery functions
,blur
等等。
Is there a way I can detect any changes on my div at any point in time ?
有什么方法可以随时检测到我的 div 上的任何变化吗?
I dont want to use any intervals or default value checked.
我不想使用任何间隔或默认值检查。
Something like this would do
像这样的事情会做
$('mydiv').contentchanged() {
alert('changed')
}
回答by iman
If you don't want use timer and check innerHTML you can try this event
如果您不想使用计时器并检查innerHTML,您可以尝试此事件
$('mydiv').bind('DOMSubtreeModified', function(){
console.log('changed');
});
More details and browser support datas are Here.
更多细节和浏览器支持数据在这里。
Attention:in newer jQuery versions bind() is deprecated, so you should use on() instead:
注意:在较新的 jQuery 版本中,不推荐使用 bind(),因此您应该使用 on() 代替:
$('body').on('DOMSubtreeModified', 'mydiv', function(){
console.log('changed');
});
回答by PPB
Using Javascript MutationObserver
使用 Javascript MutationObserver
//More Details https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// select the target node
var target = document.querySelector('mydiv')
// create an observer instance
var observer = new MutationObserver(function(mutations) {
console.log($('mydiv').text());
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
回答by Artley
Since $("#selector").bind()
is deprecated, you should use:
由于$("#selector").bind()
已弃用,您应该使用:
$("body").on('DOMSubtreeModified', "#selector", function() {
// code here
});
回答by user1790464
You can try this
你可以试试这个
$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {
});
but this might not work in internet explorer, haven't tested it
但这在 Internet Explorer 中可能不起作用,还没有测试过
回答by rodneyrehm
You are looking for MutationObserveror Mutation Events. Neither are supported everywhere nor are looked upon too fondly by the developer world.
您正在寻找MutationObserver或Mutation Events。既不受任何地方的支持,也不受开发者世界的喜爱。
If you know (and can make sure that) the div's size will change, you may be able to use the crossbrowser resize event.
如果您知道(并且可以确保)div 的大小会发生变化,您可以使用crossbrowser resize event。
回答by Sanchit Gupta
Following code works for me.
以下代码对我有用。
$("body").on('DOMSubtreeModified', "mydiv", function() {
alert('changed');
});
Hope it will help someone :)
希望它会帮助某人:)
回答by Sameera Millavithanachchi
There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.
这个问题没有内置的解决方案,这是你的设计和编码模式的问题。
You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.
您可以使用发布者/订阅者模式。为此,您可以使用 jQuery 自定义事件或您自己的事件机制。
First,
第一的,
function changeHtml(selector, html) {
var elem = $(selector);
jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
elem.html(html);
jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}
Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,
现在您可以按如下方式订阅 divhtmlchanged/divhtmlchanged 事件,
$(document).bind('htmlchanging', function (e, data) {
//your before changing html, logic goes here
});
$(document).bind('htmlchanged', function (e, data) {
//your after changed html, logic goes here
});
Now, you have to change your div content changes through this changeHtml()
function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.
现在,您必须通过此changeHtml()
功能更改您的 div 内容。因此,您可以监视或可以相应地进行必要的更改,因为绑定包含信息的回调数据参数。
You have to change your div's html like this;
您必须像这样更改 div 的 html;
changeHtml('#mydiv', '<p>test content</p>');
And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).
而且,您可以将它用于除输入元素之外的任何 html 元素。无论如何,您可以修改它以与任何元素一起使用。
回答by Anthony Awuley
Use MutationObserveras seen in this snippet provided by Mozilla, and adapted from this blog post
使用Mozilla提供的这个片段中看到的MutationObserver,并改编自这篇博文
Alternatively, you can use the JQuery example seen in this link
或者,您可以使用此链接中的 JQuery 示例
Chrome 18+, Firefox 14+, IE 11+, Safari 6+
Chrome 18+、Firefox 14+、IE 11+、Safari 6+
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// 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.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
回答by codelove
You can store the old innerHTML of the div in a variable. Set an interval to check if the old content matches the current content. When this isn't true do something.
您可以将 div 的旧 innerHTML 存储在变量中。设置一个时间间隔来检查旧内容是否与当前内容匹配。当这不是真的时,做点什么。
回答by juFo
Try the MutationObserver:
试试 MutationObserver:
- https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/
- https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
- https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/
- https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
browser support: http://caniuse.com/#feat=mutationobserver
浏览器支持:http: //caniuse.com/#feat=mutationobserver
<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>