代码之家  ›  专栏  ›  技术社区  ›  rxmnnxfpvg

jquery监视分区

  •  30
  • rxmnnxfpvg  · 技术社区  · 15 年前

    如果DIV中的内容发生更改,是否有任何方法可以监视?

    假设我有:

    <div id="hello"><p>Some content here</p></div>
    

    在5秒后的某个时刻,它变为:

    <div id="hello"><ul><li>This is totally different!</li></ul></div>
    

    如何通过回调或其他方式通知我?告诉我,在大多数情况下,我可以得到执行插入操作的javascript。但我想知道这是否可行。

    6 回复  |  直到 9 年前
        1
  •  63
  •   Sebastián Grignoli    13 年前

    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>
    

    请注意,这只监视元素(HTML)内容的更改,而不监视属性。

        2
  •  5
  •   gnarf    15 年前

    没有本地jquery/dom事件会在HTML/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);
      }
    });
    

    记住,打电话来 .html() 每100毫秒可能不是网站性能的最佳选择。

    jsFiddle mockup

        3
  •  2
  •   Nixter    13 年前

    也许,监控修改层内容的事件源是合理的?比如,用户在内容发生变化后点击了任何地方(读作“点击”)。因此,如果在单击之后检查.html(),而不是使用循环,它可能会节省一些系统资源。

        4
  •  1
  •   psychotik    15 年前

    谁/什么会改变这个?如果您控制的是一些JS,那么也可以使用它来触发回调。显然,用户无法更改此设置。

    如果你想看 <input> 元素等,使用“更改”事件。这里是jquery版本: http://api.jquery.com/change/

        5
  •  0
  •   a7drew    15 年前

    下面是一个代码示例,当给定值更改时调用一个简单警报:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>watchu, watchu, watchu want, watchu want?</title>
    </head>
    <body>
    
        <div id='foo'>Hello World!</div>
    
        <p><input type="button" id="ChangeButton" value="Change It" /></p>
    
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">
    
            $(function () {
    
                $('#ChangeButton').click(function () {
                    $('#foo').html('Awfveeterzain!');
                });
    
                window.watchForChangeOriginalValue = $('#foo').html();
                watchForChange();
            });
    
            function watchForChange() {
                if ($('#foo').html() != window.watchForChangeOriginalValue)
                    alert('the value changed!');
                else
                    window.setTimeout(watchForChange, 500);
            }
    
        </script>
    </body>
    </html>
    
        6
  •  0
  •   Prem    9 年前

    有一些事件叫做 DOMNodeInserted , DOMNodeRemoved DOMSubtreeModified . 检查是否有任何元素被添加或删除,或者在一个分区内有任何内部HTML更改。为此,您需要 setInterval() 功能。

     function DivChange() {      
        $('#YourDiv').bind('DOMNodeInserted DOMNodeRemoved', function (event) {
            if (event.type == 'DOMNodeInserted') {
                alert('Content added');
            } else if (event.type == 'DOMNodeRemoved')  {
                alert('Content removed');
            } else {
                alert('Inner Html changed for some content');
            }
        });
    }
    var DivTimer = setInterval(DivChange, 1000);
    

    上面的函数将每隔一秒钟检查DIV的内容是否发生更改。

    注意:IE不支持此事件