4

有什么方法可以捕捉到document.createElement()事件吗?

例如,某处,在<body>我有的部分内

<script>
    var div = document.createElement("div");
<script>

是否可以从该<head>部分跟踪该事件(使用一些 addEventListener、突变观察者或任何其他方式)?

注意:我需要跟踪元素的创建,而不是插入

4

3 回答 3

4

警告此代码不适用于所有浏览器。当涉及到 IE 时,所有的赌注都没有了。

(function() {
  // Step1: Save a reference to old createElement so we can call it later.
  var oldCreate = document.createElement;

  // Step 2: Create a new function that intercepts the createElement call
  // and logs it.  You can do whatever else you need to do.
  var create = function(type) {
    console.log("Creating: " + type);
    return oldCreate.call(document, type);
  }

  // Step 3: Replace document.createElement with our custom call.
  document.createElement = create;

}());
于 2014-04-15T22:20:24.053 回答
2

与其他答案类似,这是一个不完美且不完整的解决方案(并且在 Windows 8.1 上的 Chrome 34 中进行了明确测试):

// creating a function to act as a wrapper to document.createElement:
document.create = function(elType){
    // creating the new element:
    var elem = document.createElement(elType),
        // creating a custom event (called 'elementCreated'):
        evt = new CustomEvent('elementCreated', {
            // details of the custom event:
            'detail' : {
                // what was created:
                'elementType' : elem.tagName,
                // a reference to the created node:
                'elementNode' : elem
            }
    });
    // dispatching the event:
    this.dispatchEvent(evt);

    // returning the created element:
    return elem;
};

// assigning an event-handler to listen for the 'elementCreated' event:
document.addEventListener('elementCreated', function(e){
    // react as you like to the creation of a new element (using 'document.create()'):
    console.log(e);
});

// creating a new element using the above function:
var newDiv = document.create('div');

JS 小提琴演示

参考:

于 2014-04-15T22:46:38.737 回答
1

可以在 javascript 中创建自定义事件。它也被所有浏览器支持。

看看:http: //jsfiddle.net/JZwB4/1/

document.createElement = (function(){
    var orig = document.createElement;
    var event = new CustomEvent("elemCreated");
    return function() { 
        document.body.dispatchEvent(event);
        orig.call(document,x); 
    };
})();


document.body.addEventListener('elemCreated', function(){
    console.log('created');
},false);

var x= document.createElement('p'); //"created" in console
于 2014-04-15T22:47:08.007 回答