jQuery监视domElement的变化? [英] jQuery watch for domElement changes?

查看:124
本文介绍了jQuery监视domElement的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ajax回调,它将html标记注入一个页脚div。

I have an ajax callback which injects html markup into a footer div.

我无法弄清楚如何创建监视div的方法当它的内容发生变化时。放置我试图在回调中创建的布局逻辑不是一个选项,因为每个方法(回调和我的布局div处理程序)都不应该知道另一个。

What I can't figure out is how to create a way to monitor the div for when it's contents change. Placing the layout logic I'm trying to create in the callback isn't an option as each method (callback and my layout div handler) shouldn't know about the other.

理想情况下,我希望看到某种事件处理程序类似于 $('#myDiv')。ContentsChanged(function(){...}) $('#myDiv')。TriggerWhenContentExists(function(){...})

Ideally I'd like to see some kind of event handler akin to $('#myDiv').ContentsChanged(function() {...}) or $('#myDiv').TriggerWhenContentExists( function() {...})

我找到了一个插件称为watch和该插件的改进版本,但永远无法触发。我试着观察我能想到的一切(即通过ajax注射改变了div的高度属性),但却无法让它们做任何事情。

I found a plugin called watch and an improved version of that plugin but could never get either to trigger. I tried "watching" everything I could think of (i.e. height property of the div being changed via the ajax injection) but couldn't get them to do anything at all.

有什么想法/帮助吗?
谢谢
jas

Any thoughts/help? Thanks jas

推荐答案

我发现最有效的方法是绑定到 DOMSubtreeModified 事件。它适用于jQuery的 $。html()以及标准JavaScript的 innerHTML 属性。

The most effective way I've found is to bind to the DOMSubtreeModified event. It works well with both jQuery's $.html() and via standard JavaScript's innerHTML property.

$('#content').bind('DOMSubtreeModified', function(e) {
  if (e.target.innerHTML.length > 0) {
    // Content change handler
  }
});

http:// jsfiddle.net/hnCxK/

从jQuery的 $。html()调用时,我发现该事件触发两次:一次清除现有内容,一次设置。一个快速的 .length -check将在简单的实现中工作。

When called from jQuery's $.html(), I found the event fires twice: once to clear existing contents and once to set it. A quick .length-check will work in simple implementations.

同样重要的是要注意事件将<设置为HTML字符串时强烈>始终触发(即'< p> Hello,world< / p>')。而且,对于纯文本字符串,事件只会在触发时触发。

It's also important to note that the event will always fire when set to an HTML string (ie '<p>Hello, world</p>'). And that the event will only fire when changed for plain-text strings.

这篇关于jQuery监视domElement的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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