1

我需要捕捉 $.append() 方法,像这样

$('div').bind('append', function(){
    /* code here */
});

或者

$('div').bind('html', function(){
    /* code here */
});

我怎么能得到这个?

4

1 回答 1

0

在您追加内容的所有地方,触发自定义事件:

$('#bar').append('...');
$.event.trigger('customappend');

...并在您附加代码的所有地方触发它:

$('#foo').append('...');
$.event.trigger('customappend');

在一个地方收听:

$(document).on('customappend', function(){
    /* code here */
});

解决方案#2(使用MutationObserver):

// select the target node
var target = document.querySelector('#id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('target mutated');
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
// observer.disconnect();

$(document).click(function(){
    $('#id').append('.');
});

http://jsfiddle.net/VTmk5/1/

于 2013-11-04T11:39:40.103 回答