How to use a real-time switching event?

I have the following code

$(".reply").toggle ( function () { x1(); }, function () { x2(); } ); 

I need to use live , so new items will also be linked. Is there any syntax? Or do I need to implement toggle in a click event?

I am using jQuery 1.4.2.

+7
jquery events
source share
2 answers

The just modified fehay answer so it doesn't rely on jQuery without adding duplicate event handlers during toggle()

 $(".reply").live('click', function () { var toggled = $(this).data('toggled'); $(this).data('toggled', !toggled); if (!toggled) { x1(); } else { x2(); } }); 

Also, keep in mind that selectors for live should be as specific as possible because of how event delegation works. Every time something clicks on a document, jQuery has to climb the tree, checking if the element matches the selector. For the same reason .delegate() much more efficient because you can limit the scope of capture.

+13
source share

live supports custom events in jQuery 1.4. You can try something like this:

 $(function () { $(".reply").live("customToggle", function () { $(this).toggle( function () { x1(); }, function () { x2(); } ); }); $(".reply").live('click', function () { $(this).trigger('customToggle'); }); }); 

It looks like it works fine without a special event:

 $(".reply").live('click', function () { $(this).toggle( function () { x1(); }, function () { x2(); } ); $(this).trigger('click'); }); 
+3
source share

All Articles