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 に答える