在div更改时触发jQuery事件 [英] Fire jQuery event on div change

查看:189
本文介绍了在div更改时触发jQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其内容可能会以各种方式改变:例如,它的整个内容可以通过innerHTML重新加载,或者节点可以通过DOM方法添加。这反过来可能通过本机javascript或通过调用jQuery API或通过其他库间接发生。

I have a div whose content may change in various ways: for instance its whole content may be reloaded via innerHTML, or nodes may be added via DOM methods. This in turn may happen via native javascript or indirectly via calls the jQuery API or via other libraries.

我想在div的内容发生变化时执行一些代码,但是我对 的更改方式绝对无法控制。事实上,我正在设计一个可供其他人使用的小部件,他们可以按自己喜欢的方式自由更改div的内容。当这个div的内部内容发生变化时,小部件的形状也可能需要更新。

I want to execute some code when the content of the div changes, but I have absolutely no control on how it will change. Indeed I am designing a widget that may be used by other people, who are free to change the content of their divs the way they prefer. When the inner content of this div changes, the shape of the widget may have to be updated as well.

我正在使用jQuery。有没有办法捕获这个div的内容发生了变化的事件,但它发生了什么?

I'm using jQuery. Is there a way to capture the event that the content of this div has changed, however it happened?

推荐答案

你可以用 DOMNodeInserted DOMNodeRemoved 检查是否添加或删除了元素。不幸的是,IE不支持这一点。

You can use DOMNodeInserted and DOMNodeRemoved to check if elements are added or removed. Unfortunately, IE doesn't support this.

$('#myDiv').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
    if (event.type == 'DOMNodeInserted') {
        alert('Content added! Current content:' + '\n\n' + this.innerHTML);
    } else {
        alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
    }
});






更新



您可以使用 .data()保存初始内容和将来的更改。这是一个例子。


Update

You could save the initial contents and future changes with .data(). Here's an example.

var div_eTypes = [],
    div_changes = [];
$(function() {
    $('#myDiv').each(function() {
        this['data-initialContents'] = this.innerHTML;
    }).bind('DOMNodeInserted DOMNodeRemoved', function(event) {
        div_eTypes.concat(e.type.match(/insert|remove/));
        div_changes.concat(this.innerHTML);
    });
});

示例输出:

> $('#myDiv').data('initialContents');
"<h1>Hello, world!</h1><p>This is an example.</p>"
> div_eTypes;
["insert", "insert", "remove"]
> div_changes;
["<iframe src='http://example.com'></iframe>", "<h4>IANA — Example domains</h4><iframe src='http://example.com'></iframe>", "<h4>IANA – Example domains</h4>"]






更新2



您可能想要包含 DOMSubtreeModified 同样,因为我发现 DOMNodeInserted DOMNodeRemoved 不会触发元素的 innerHTML 将被直接替换。它仍然无法在IE中运行,但至少它在其他浏览器中工作正常。


Update 2

You may want to include DOMSubtreeModified as well, because I've found out that DOMNodeInserted and DOMNodeRemoved don't trigger if an element's innerHTML is replaced directly. It still doesn't work in IE, but at least it works fine in other browsers.

这篇关于在div更改时触发jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆