jquery监听div内容的变化具体实现思路

  我们做电子商务,javascript框架采用的是jQuery,在开发过程中遇到了上面标题列出的问题:如何监听div内容的变化。

  先给出最终代码(后续进行相关分析):

  

复制代码 代码如下:

  var title = $("b.facility");

  var title = $('#title');//the element I want to monitor

  title.bind('DOMNodeInserted', function(e) {

  alert('element now contains: ' + $(e.target).html());

  });

  解决问题的思路如下:

  我们先回顾一下jQuery事件中的change()方法定义和用法:

  当元素的值发生改变时,会发生 change 事件。

  该事件仅适用于文本域(text field),以及 textarea 和 select 元素。

  change() 函数触发 change 事件,或规定当发生 change 事件时运行的函数。

  注释:当用于 select 元素时,change 事件会在选择某个选项时发生。当用于 text field 或 text area 时,该事件会在元素失去焦点时发生。

  但是问题出现了关于div内容的改变change方法中只字不提,我们如何处理那?

  后续百度关键词: jquery div 内容发生变化:无果;

  继续,bing关键词:jquery how to listen div change 找到一篇相关文档http://stackoverflow.com/questions/2712124/jquery-listen-to-changes-within-a-div-and-act-accordingly

  粗略的明白是采用自定义事件的方式去处理问题,采纳代码如下:

  

复制代码 代码如下:

  $('#laneconfigdisplay').bind('contentchanged', function() {

  // do something after the div content has changed

  alert('woo');

  });

  // 这样会调用上面的函数

  $('#laneconfigdisplay').trigger('contentchanged');

  但是contentchanged是什么内容没有说明,继续追溯

  bing关键词:jquery how to listen div change 找到一篇相关文档

  继续,bing关键词:jquery contentchanged 找到一篇相关文档http://stackoverflow.com/questions/1449666/create-a-jquery-special-event-for-content-changed

  这篇文章详细说明了contentchanged内容定义,采纳代码如下:

  

复制代码 代码如下:

  jQuery.fn.watch = function( id, fn ) {

  returnthis.each(function(){

  var self = this;

  var oldVal = self[id];

  $(self).data(

  'watch_timer',

  setInterval(function(){

  if(self[id] !== oldVal) {

  fn.call(self, id, oldVal, self[id]);

  oldVal = self[id];

  }

  },100)

  );

  });

  returnself;

  };

  jQuery.fn.unwatch = function( id ) {

  returnthis.each(function(){

  clearInterval( $(this).data('watch_timer') );

  });

  };

  创建自定义事件

  

复制代码 代码如下:

  jQuery.fn.valuechange = function(fn) {

  returnthis.bind('valuechange', fn);

  };

  jQuery.event.special.valuechange = {

  setup: function() {

  jQuery(this).watch('value', function(){

  jQuery.event.handle.call(this, {type:'valuechange'});

  });

  },

  teardown: function() {

  jQuery(this).unwatch('value');

  }

  };

  貌似这样的解决是完美的但是后续再继续查看到时候,发现有更简洁的方式,代码如下:

  

复制代码 代码如下:

  var title = $("b.facility");

  var title = $('#title');//the element I want to monitor

  title.bind('DOMNodeInserted', function(e) {

  alert('element now contains: ' + $(e.target).html());

  });

  感觉这应该是我需要代码,do it !fine