我想执行一个函数时,一些div或输入被添加到html。 这可能吗?

例如,添加了一个文本输入,然后应该调用函数。


当前回答

我最近写了一个插件,就是这样做的——jquery.initialize

你可以像使用.each函数一样使用它

$(".some-element").initialize( function(){
    $(this).css("color", "blue"); 
});

与.each的不同之处在于-它接受你的选择器,在本例中是.some-element,并等待将来使用该选择器的新元素,如果添加了这样的元素,它也将被初始化。

在我们的例子中,初始化函数只是将元素颜色改为蓝色。因此,如果我们添加新元素(无论是使用ajax还是F12检查器或任何东西),如:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

插件会立即初始化它。另外,plugin确保一个元素只初始化一次。因此,如果您添加了element,然后.detach()它从body中,然后再次添加它,它将不会再次初始化。

$("<div/>").addClass('some-element').appendTo("body").detach()
    .appendTo(".some-container");
//initialized only once

插件基于MutationObserver -它将在IE9和ie10上工作,并在自述页面上详细说明依赖关系。

其他回答

使用MutationObserver界面,如Gabriele Romanato的博客所示

找到了,Chrome 18+,火狐14+

// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
        var $nodes = $( newNodes ); // jQuery set
        $nodes.each(function() {
            var $node = $( this );
            if( $node.hasClass( "message" ) ) {
                // do something
            }
        });
    }
  });    
});

// 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();

8年后,这是我使用MutationObserver和RxJS的解决方案

observeDOMChange(document.querySelector('#dom-changes-here'))
  .subscribe(val => log('DOM-change detected'));

与其他方法的主要区别是在DOM更改时触发CustomEvent,并通过以下特性侦听事件的恢复以有效地执行用户逻辑;

撤消连续的DOM更改,以防止执行过多 在给定的时间后停止观看 在停止监视DOM更改后删除事件侦听器/订阅者 观察一个框架(比如Angular)中发生的DOM变化是很有用的

import { fromEvent, timer} from 'rxjs';
import { debounceTime, takeUntil, tap } from 'rxjs/operators';

function observeDOMChange(el, options={}) {
  options = Object.assign({debounce: 100, expires: 2000}, options);

  const observer = new MutationObserver(list =>  {
    el.dispatchEvent(new CustomEvent('dom-change', {detail: list}));
  });
  observer.observe(el, {attributes: false, childList: true, subtree: true });

  let pipeFn;
  if (options.expires) {
    setTimeout(_ => observer.disconnect(), options.expires);
    pipeFn = takeUntil(timer(options.expires));
  } else {
    pipeFn = tap(_ => _); 
  }

  return fromEvent(el, 'dom-change')
    .pipe(pipeFn, debounceTime(options.debounce));
}

在stackblitz演示。

如何为这个扩展jquery ?

   (function () {
        var ev = new $.Event('remove'),
            orig = $.fn.remove;
        var evap = new $.Event('append'),
           origap = $.fn.append;
        $.fn.remove = function () {
            $(this).trigger(ev);
            return orig.apply(this, arguments);
        }
        $.fn.append = function () {
            $(this).trigger(evap);
            return origap.apply(this, arguments);
        }
    })();
    $(document).on('append', function (e) { /*write your logic here*/ });
    $(document).on('remove', function (e) { /*write your logic here*/ });

Jquery 1.9+已经建立了对此的支持(我听说没有测试过)。

下面的例子改编自Mozilla Hacks的博客文章,并使用MutationObserver。

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

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

浏览器支持:Chrome 18+, Firefox 14+, IE 11+, Safari 6+

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

完整解释:https://stackoverflow.com/a/11546242/6569224