jQuery事件:检测对div的html /文本的更改

Boq*_*Boq 255 jquery jquery-ui

我有有它的所有内容改变时间一个div,无论是ajax requests,jquery functions,blur等等等等.

有没有办法可以在任何时间点检测到我的div上的任何变化?

我不想使用任何间隔或默认值检查.

像这样的东西会做

$('mydiv').contentchanged() {
 alert('changed')
}
Run Code Online (Sandbox Code Playgroud)

ima*_*man 382

如果您不想使用计时器并检查innerHTML,您可以尝试此事件

$('mydiv').bind("DOMSubtreeModified",function(){
  alert('changed');
});
Run Code Online (Sandbox Code Playgroud)

更多细节和浏览器支持数据在这里.

注意:在较新的jQuery版本中,不推荐使用bind(),因此您应该使用on()代替:

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});
Run Code Online (Sandbox Code Playgroud)

  • 此事件已弃用http://www.w3.org/TR/DOM-Level-3-Events/#glossary-deprecated (55认同)
  • 此方法已被弃用!而是使用:`$("body").on('DOMSubtreeModified',"mydiv",function(){});` (19认同)
  • 这是严重的不要使用这个事件它会崩溃你的所有工作因为它一直被解雇.而是使用$('.myDiv')下面的事件.bob('DOMNodeInserted DOMNodeRemoved',function(){}); (15认同)
  • 请记住,IE8(及以下版本)不支持DOMSubtreeModified. (14认同)
  • Mozilla 33:在元素<body>的递归中失败了.需要找到另一种方式 (3认同)

Art*_*ley 47

由于$("#selector").bind()不推荐使用,您应该使用:

$("body").on('DOMSubtreeModified', "#selector", function() {
    // code here
});
Run Code Online (Sandbox Code Playgroud)


小智 40

你可以试试这个

$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {

});
Run Code Online (Sandbox Code Playgroud)

但这可能不适用于Internet Explorer,尚未测试过

  • 解释:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events改为使用:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver (9认同)
  • 注意!:如果你使用它作为触发器并且对页面进行了很多更改 - 它将运行你的函数X次(甚至X = 1,000或更多),这可能是非常低效的.一个简单的解决方案是定义一个"正在运行"的布尔变量,它将... if(running == true){return} ...如果它已经在运行,则不运行代码.在if逻辑之后设置running = true,并在函数退出之前运行= false.您还可以使用计时器将您的功能限制为只能每X秒运行一次.运行= TRUE; 的setTimeout(函数(){运行= FALSE},5000); (或更好的东西) (3认同)
  • @JxAxMxIxN您还可以通过再次清除和设置超时来缓冲超时计时器:`clearTimeout(window.something); window.something = setTimeout(...);` (2认同)

PPB*_*PPB 38

使用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);
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,因为现在比使用DOMSubtreeModified更受青睐 (2认同)
  • 即使我提供了正确的选择器,我也对此出错。“ VM21504:819未捕获的TypeError:无法在'MutationObserver'上执行'观察':参数1的类型不是'节点'。” (2认同)

rod*_*ehm 33

您正在寻找MutationObserverMutation Events.既没有在任何地方得到支持,也没有被开发者世界过于喜爱地看待.

如果你知道(并且可以确定)div的大小会改变,你可以使用crossbrowser resize事件.

  • 如果其他人不得不尝试阅读所有地方,这是正确的答案.变异事件在过去的浏览器中得到支持,Mutation Observer是现代浏览器所支持的,并且将来会得到支持.请参阅链接以获取支持:[CANIUSE Mutation Observer](http://caniuse.com/#feat=mutationobserver) (9认同)

San*_*pta 20

以下代码适合我.

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});
Run Code Online (Sandbox Code Playgroud)

希望它会帮助别人:)


Sam*_*chi 17

没有针对此问题的内置解决方案,这是您的设计和编码模式的问题.

您可以使用发布者/订阅者模式.为此,您可以使用jQuery自定义事件或您自己的事件机制.

第一,

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 });
}
Run Code Online (Sandbox Code Playgroud)

现在您可以订阅divhtmlchanging/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
});
Run Code Online (Sandbox Code Playgroud)

现在,您必须通过此changeHtml()功能更改div内容更改.因此,您可以监视或可以相应地进行必要的更改,因为绑定包含该信息的回调数据参数.

你必须像这样改变你的div的html;

changeHtml('#mydiv', '<p>test content</p>');
Run Code Online (Sandbox Code Playgroud)

此外,您可以将此用于除输入元素之外的任何html元素.无论如何,你可以修改它以使用任何元素.

  • "这是您的设计和编码模式的问题",如果您包含第三方脚本该怎么办,因此您无法控制其源代码?但你需要检测他们对一个div的更改? (8认同)

Ant*_*ley 8

使用MutationObserver,Mozilla提供的此片段中所示,并改编自此博客文章

或者,您可以使用此链接中显示的JQuery示例

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();
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试了上面给出的一些答案,但这些火灾发生了两次。如果您可能需要相同的解决方案,这是可行的解决方案。

$('mydiv').one('DOMSubtreeModified', function(){
    console.log('changed');
});
Run Code Online (Sandbox Code Playgroud)