开发者

Re-attach event to newly loaded div

Apparently my JQuery events die when the elements are replaced. Currently they are attached like this:

$("a[id^='anb']").click(
        function () {
            /* ommited for readability */;
            var furl = "target_vi开发者_Python百科ew";
            $('#my_article_container').load(furl, function() {
                       animateThem(); });
            return false;
        }

    );

    $("div[id^='art']").hover(
        function() {
            $(this).fadeTo("slow", 0.33);
        }
    );

Is there a mechanisme inside JQuery or a handy work around on how to re-bind these events?


You're looking for the .live() function.

This will monitor the dom and reattach events automatically as items are added.

$("a[id^='anb']").live('click',
    function () {
        /* ommited for readability */;
        var furl = "target_view";
        $('#my_article_container').load(furl, function() {
                   animateThem(); });
        return false;
    }

);

$("div[id^='art']").live('hover',
    function() {
        $(this).fadeTo("slow", 0.33);
    }
);


This was the first answer that came up when I googled it - me having the same problem. Live has been deprecated in version 1.7 and removed in version 1.9. The new versions of JQuery recommend using on. jQuery.on()

Anyway, just to keep this up to date. I the end I got mine to work by including the selector in the on function eg:

$(document).on("click","a[id^='anb']",function(){....})


Use the live function instead.


Use $.live() instead, which is designed to work for this very case.

$("a[id^='anb']").live('click', function() { ... });
$("a[id^='art']").live('hover', function() { ... });


Live is your friend


I believe you're looking for jQuery.live()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜