jQuery 监视 domElement 的变化?

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

问题描述

我有一个将 html 标记注入页脚 div 的 ajax 回调.

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.

有什么想法/帮助吗?

推荐答案

我发现最有效的方法是绑定到 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-检查将在简单的实现中起作用.

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 的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)