简体   繁体   English

观察特定DIV的内容

[英]Observing contents of a specific DIV

Is there a way to Observe the Contents of a specific DIV, I want to call a function as soon as the contents of the DIV are Changed. 有没有一种方法可以观察特定DIV的内容,我想在DIV的内容更改后立即调用一个函数。

This can be a innerHTML replace, a page load. 这可以是innerHTML替换,也可以是页面加载。

Thanks 谢谢

In modern browsers you can use DOM mutation events like DOMSubtreeModified , DOMCharacterDataModified . 在现代浏览器中,您可以使用DOM突变事件,例如DOMSubtreeModifiedDOMCharacterDataModified In IE you've got onchange event which you can use. 在IE中,您可以使用onchange事件。 For all the other browsers you can set up a timer for checking if the content has been changed. 对于所有其他浏览器,您可以设置一个计时器以检查内容是否已更改。

You can check the contents of the element comparing to the previous value. 您可以将元素的内容与先前的值进行比较。

Retrieve the element to watch 检索要观看的元素

var div = document.getElementById("w");

Create a watcher: 创建观察者:

var w1 = { watch: null, prev: div.innerHTML };

Start the watcher. 启动观察程序。 Each 100ms it will compare the previous value to the current value, if it's different it will update the value and trigger any actions. 每100毫秒,它将把先前的值与当前值进行比较,如果不同,它将更新该值并触发任何动作。

function Watch(w, e)
{
    w.watch = setInterval(function() {
       if (e.innerHTML != w.prev)
       {
           w.prev = e.innerHTML;
           alert("changed");
       }
    }, 100);
}

Watch(w1, div);

See this example on jsFiddle. 请参阅jsFiddle上的示例。

In this page , it says that DIVs should fire OnChange when their content is modified. 此页面中 ,它说,DIV的内容被修改时应触发OnChange。

Observing a div for change is not an effective technique. 观察div的变化不是有效的技术。 Have you looked into getting the code that changes the DIV's content to trigger and event? 您是否考虑过获得将DIV的内容更改为触发和事件的代码?

Alternatively you could set a timer that monitors changes in your div and triggers some event. 另外,您可以设置一个计时器来监视div中的更改并触发某些事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM