jQuery watch div

atp*_*atp 30 jquery

如果div中的内容发生变化,有没有办法观看?

比方说我有:

<div id="hello"><p>Some content here</p></div>
Run Code Online (Sandbox Code Playgroud)

在5秒后的某个时间点变为:

<div id="hello"><ul><li>This is totally different!</li></ul></div>
Run Code Online (Sandbox Code Playgroud)

如何通过回调或其他方式通知此事?在大多数情况下,我可以获取正在插入的javascript,告诉我.但我想知道它是否可能.

Seb*_*oli 63

jQuery .change()方法仅适用于表单字段.

我为你写了一个小jQuery插件:

<!-- jQuery is required -->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>


<!-- this is the plugin -->

<script>
  jQuery.fn.contentChange = function(callback){
    var elms = jQuery(this);
    elms.each(
      function(i){
        var elm = jQuery(this);
        elm.data("lastContents", elm.html());
        window.watchContentChange = window.watchContentChange ? window.watchContentChange : [];
        window.watchContentChange.push({"element": elm, "callback": callback});
      }
    )
    return elms;
  }
  setInterval(function(){
    if(window.watchContentChange){
      for( i in window.watchContentChange){
        if(window.watchContentChange[i].element.data("lastContents") != window.watchContentChange[i].element.html()){
          window.watchContentChange[i].callback.apply(window.watchContentChange[i].element);
          window.watchContentChange[i].element.data("lastContents", window.watchContentChange[i].element.html())
        };
      }
    }
  },500);
</script>



<!-- some divs to test it with -->

<p>Testing it:  (click on divs to change contents)</p>

<div id="a" onclick="$(this).append('i')">Hi</div>
<div id="b" onclick="$(this).append('o')">Ho</div>
<div class="c" onclick="$(this).append('y')">He</div>
<div class="c" onclick="$(this).append('w')">He</div>
<div class="c" onclick="$(this).append('a')">He</div>




<!-- this is how to actually use it -->

<script>
  function showChange(){
    var element = $(this);
    alert("it was '"+element.data("lastContents")+"' and now its '"+element.html()+"'");
  }

  $('#a').contentChange(function(){  alert("Hi!") });
  $('div#b').contentChange( showChange );
  $('.c').contentChange(function(){  alert("He he he...") });
</script>
Run Code Online (Sandbox Code Playgroud)

请注意,这只会监视元素(html)内容的变化,而不是属性.

  • 谢谢.显然,唯一的方法是手动设置计时器.我可能永远不需要使用插件,但感谢你写这个插件. (2认同)

gna*_*arf 6

当HTML/DOM内容发生变化时,不会触发本机jQuery/DOM事件.

你可以(如果你感觉特别浪费)做这样的事情:

$(function() {
  var $div = $("#hello");
  var html = $div.html();
  var checking = setInterval(function() {
    var newhtml = $div.html();
    if (html != newhtml) {
      myCallback();
      html = newhtml;
    }
  },100);

  function myCallback() {
    alert('content changed!');
    // if you only want it to fire once, uncomment the following:
    // clearInterval(checking);
  }
});
Run Code Online (Sandbox Code Playgroud)

请记住,.html()每100毫秒调用可能不是您网站性能的最佳选择.

jsFiddle模型