问题
I want a certain callback executed each time a div satisfying a certain selector is inserted into a DOM. I've poked around the DOM events documentation, and the closest event I've found to what I need is "load", but it doesn't quite work as I hope.
Ideally I want something along the lines of:
$(".myclass").live("load", function(){... do stuff to $(this) ...}
To give some context to what I'm doing:
I have an event on a webpage which creates new forms each time some button is clicked. Modifying that JS code is highly undesirable. I want to convert one of the fields in the form into jstree, so the only approach I was able to think of is to attach a callback for insertion-into-DOM-event and attach a jstree inside a func.
Update: I've found DOMNodeInserted, but apparently it's not supported in IE.
回答1:
Massive Warning: DOMMutationEvents as defined in DOM level 3 are deprecated.
document.addEventListener("DOMNodeInserted", function (ev) {
var node = ev.target;
if (careAbout(node)) {
runCode(ev);
}
});
The DOMNodeInserted
event is documented in DOM events level 2.
Of course browser support is mediocre.
The only way to emulate this in non-compliant browsers is polling the entire DOM for whether the tree has changed and firing events by hand. This is also know as expensive as hell.
But your real problem:
Modifying that JS code is highly undesirable
You have bad, ugly, unmaintainable code. Ignoring it isn't going to solve the problem. Stepping around it isn't going to make it go away. The best thing to do is to refactor, refactor, refactor.
来源:https://stackoverflow.com/questions/7989411/dom-callback-for-node-creation