Observing for insertion of new DOM nodes and calling a method on them
I'm writing some javascript using jQuery to call a method on all nodes with class datepicker
.
Here's what I have:
$('.datepicker').my_method();
This works as expected - it call开发者_Python百科s my_method
.
However, I want to be able to call my_method
on all new nodes that are inserted into the DOM with the class datepicker
.
I want similar functionality to the .live
method, without specifying an eventType
.
How do I go about this?
This is what the .livequery
plugin is for :)
You use it like this
$('.datepicker').livequery(function() {
$(this).my_method();
});
Alternatively, you can re-run your plugin when you're loading elements, say in the case of $.ajax()
, like this:
$.ajax({
//options..
success: function(data) {
$("#elementId").html(data);
$(".datepicker", data).my_method();
}
});
This method only runs on .datepicker
elements in the response, not existing ones...so it's only running/doing the minimal amount of work. This is the most efficient approach in terms of wasted observation code/processing, etc...but it's not always an option.
精彩评论