I know I can do this:
$("#my_div").live("click", function() {
alert("My Div was clicked");开发者_运维百科
}
But how can I define a handler to call when a matching element is loaded to the DOM (now or in future)?
Have a look at Live Query. It allow you to fire events when matching elements get added to the DOM.
The only way I can think of to achieve this, without using a plug-in, is:
$('selecter').bind('DOMNodeInserted',
function(){
if ($('.newElementClassName').length > countOfNewDivs) {
// new element matching new element's class-name has been added
countOfNewDivs++;
alert(countOfNewDivs);
}
});
JS Fiddle demo.
Note:
This has only been tested on Chromium 11, and Firefox 4, on Ubuntu 11.04; I don't think that this approach is likely to work in IE, but I'm unable to test.
One way of doing this is assigning all common divs the same class and using:
$(".myDIVClass").live("click", function() {
alert("My Div was clicked");
}
精彩评论