如何检测HTML元素内容的变化? [英] How to detect a change in the contents of a HTML element?
问题描述
我正在使用 Ruby on Rails
3.1.0
和 jquery-rails
gem。我想绑定一个jQuery事件(也许我可以使用 live
功能...)到HTML div
标记,以便我可以检查其内容更改,如果是这样(即,如果新代码添加到 div
标记),则在另一个HTML中创建自定义文本 div
tag。
I am using Ruby on Rails
3.1.0
and the jquery-rails
gem. I would like to bind a jQuery event (maybe I could use the live
functionality...) to a HTML div
tag so that I can check its content changes and, if so (that is, if new code is added to the that div
tag), to create a custom text in another HTML div
tag.
也就是说,在我的视图文件中我有:
That is, in my view file I have:
<div id="div_content_1"></div>
<div id="div_content_2"></div>
我想添加\删除你好! div
内的短信 id =div_content_2
每次 div
内容 id =div_content_1
更改(在我的情况下,当HTML 输入$ c时$ c>字段被添加到
div
标记 - 阅读后面的示例)。例如(在添加的情况下),当 div
与 id =div_content_1
时,这样的变化
I would like to add\remove an "Hello!" text message inside the div
with id="div_content_2"
eachtime the div
content with id="div_content_1"
changes (in my case, when an HTML input
field is added to that div
tag - read the example that follows). For example (in the "add" case), when the div
with id="div_content_1"
changes like this
<div id="div_content_1">
<!-- The following 'input' tag was just added -->
<input ... />
</div>
我想让它工作,以便在<$ c中得到如下的输出$ c> div , id =div_content_2
:
I would like to make it to work so to have an output like the following in the div
with id="div_content_2"
:
<div id="div_content_2">
<p>
Hello!
</p>
</div>
我该怎么做?
PS :我正在为用户选择一些选项后实现一个表单(此事件旨在生成HTML 输入
div
中的字段 id =div_content_1
- 我为了我的自定义目的而制作...)可以在同一页面上订购这些选项( div
与 id =div_content_2
旨在使排序成为可能我计划的过程。
P.S.: I am implementing a form for which a user, after selecting some option (this event is intended to generate HTML input
fields in the div
with id="div_content_1"
- I make that for my custom purposes...) can order those option on the same page (the div
with id="div_content_2"
is intended to make possible the sorting process that I planned).
推荐答案
怎么样:
$('#div_content_1').bind('DOMSubtreeModified', function() {
$('#div_content_2').html('<p>Hello</p>');
});
工作示例: JSFiddle
此方法优于其他两种方法,因为它不使用轮询。相反,它使用观察者模式,这是更好的。但是,缺点是这不适用于低于9的Internet Explorer版本。
This method is better than the other two because it does not use polling. Instead, it uses the Observer pattern, which is much better. However, the downside is that this won't work in versions of Internet Explorer lower than 9.
这篇关于如何检测HTML元素内容的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!