开发者

It possible to attach a handler for when an item is loaded to the DOM in jQuery?

开发者 https://www.devze.com 2023-03-08 21:19 出处:网络
I know I can do this: $("#my_div").live("click", function() { alert("My Div was clicked");开发者_运维百科

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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消