mkotwd
mkotwd

Reputation: 21

what's the different between live and delegate

like the title said , this two function is in jquery :)

Upvotes: 0

Views: 83

Answers (4)

Pointy
Pointy

Reputation: 414086

The ".live()" API has the disadvantage of needlessly building up a jQuery object from the target selector before establishing the bubbled event handler on the <body> element. Otherwise you can express ".live()" in terms of ".delegate()":

$(something).live('click', func);

is effectively the same as

$('body').delegate(something, 'click', func);

except that the latter is more efficient because the "something" selector will not actually be applied to the page while setting up the handler.

Upvotes: 1

Patrick
Patrick

Reputation: 7722

Googled - As per the documentation on the jquery site.

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the element to which they are delegated; event handlers on any elements below it will already have been executed by the time the delegated event handler is called.

$("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
});

Is equivalent to the following code written using .live():

$("table").each(function(){
    $("td", this).live("hover", function(){
        $(this).toggleClass("hover");
    });
});

Upvotes: 4

Fender
Fender

Reputation: 3055

just read the api documentation.

delegate expects a selector as root element, whereas live does not

Upvotes: 0

Geoff Appleford
Geoff Appleford

Reputation: 18832

http://api.jquery.com/live/

http://api.jquery.com/delegate

Its all in the docs.

$("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
});

Is equivalent to the following code written using .live():

$("table").each(function(){
    $("td", this).live("hover", function(){
        $(this).toggleClass("hover");
    });
});

Upvotes: 1

Related Questions