HTML表onChange

时间:2012-09-12 10:23:00

标签: jquery html ajax onchange

我遇到了一个问题:我的表格经常被AJAX脚本更新。此更新是从Chrome插件调用的,我不想更改。所以我想添加一些jQuery触发器,在更改表格单元格时会调用我自己的函数。

有可能吗?我尝试了事件onChange,但它不起作用(如果我是正确的话,它是输入的)

提前致谢!

2 个答案:

答案 0 :(得分:4)

使用setInterval()您可以持续监控表格的内容并将其与之前的内容进行比较。如果内容不同,则表格已更改。

$(function() {
    var previous = $("#mytable").text();
    $check = function() {
        if ($("#mytable").text() != previous) {
            myOwnFunction();
        }
        previous = $("#mytable").text();        
    }
    setInterval(function() { $check(); }, 1000);
}

function myOwnFunction() {
    alert("CHANGED");
}

答案 1 :(得分:4)

onchange旨在与<select>之类的输入一起使用 - 因此在此上下文中不起作用。您可以使用(例如DOMSubtreeModified这些特定的dom相关事件,但这些事件不是跨浏览器的,并且具有不同的实现(它们甚至可能已被弃用)

http://en.wikipedia.org/wiki/DOM_events

上面提到的

MutationEvents似乎被MutationObservers所取代,我自己还没有使用过......但听起来它可以满足您的需求:

http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers

的setInterval

除此之外,您可以回退到setInterval处理程序,该处理程序将侦听目标元素中HTML的任何更改...当它发生更改时,您将触发一个函数。

function watch( targetElement, triggerFunction ){
  /// store the original html to compare with later
  var html = targetElement.innerHTML;
  /// start our constant checking function
  setInterval(function(){
    /// compare the previous html with the current
    if ( html != targetElement.innerHTML ) {
      /// trigger our function when a change occurs
      triggerFunction();
      /// update html so that this doesn't keep triggering
      html = targetElement.innerHTML;
    }
  },500);
}

function whenChangeHappens(){
  alert('this will trigger when the html changes in my_target');
}

watch( document.getElementById('my_target'), whenChangeHappens );

jQuery插件

如果您想将上述内容jQuery化为可以应用于任何元素的内容,那么很容易修改:

/// set up the very simple jQuery plugin
(function($){
  $.fn.domChange = function( whenChanged ){
     /// we want to store our setInterval statically so that we
     /// only use one for all the listeners we might create in a page
     var _static = $.fn.domChange;
     _static.calls = [];
     _static.iid = setInterval( function(){
       var i = _static.calls.length;
       while ( i-- ) {
         if ( _static.calls[i] ) {
           _static.calls[i]();
         }
       }
     }, 500 );
     /// step each element in the jQuery collection and apply a
     /// logic block that checks for the change in html
     this.each (function(){
       var target = $(this), html = target.html();
       /// by adding the function to a list we can easily switch
       /// in extra checks to the main setInterval function
       _static.calls.push (function(){
         if ( html != target.html() ) {
           html = target.html();
           whenChanged();
         }
       });
     });
  }
})(typeof jQuery != undefined && jQuery);

/// example code to test this
(function($){
  $(function(){
    $('div').domChange( function(){
      alert('I was changed!');
    } );
  });
})(typeof jQuery != undefined && jQuery);

显然上面是一个非常简单的版本,应该扩展它来处理添加和删除监听器。