简体   繁体   中英

JQueryUI SwitchClass has no effect on Javascript

Problem:

I am switching an element's display between 2 classes (" class1 " & " class2 ", say) using the JQueryUI SwitchClass() method. This is supposed to change the display back and forth, but I cannot switch back to the original class.

The $('.class1').click() function works fine, and switches the <a> element's class to " class2 ", styles and all. The $('.class2').click() function does not fire after this on clicking the same <a> element, although the CSS class has already been switched successfully. I'd like to switch the class back to " class1 " on click.

Sample Code: http://jsfiddle.net/buddhaspake/F6BE8/1/

I am pretty sure I am missing something simple... Any solution/workaround will be much appreciated!!

EDIT:

I found 2 solutions to my problem (Described below)
1. SOLUTION to SwitchClass() issue:
(As suggested by Rajaprabhu): to use jQuery Event-delegation model to add a istener to an outer element (the nearest static parent).
Sample code here: http://jsfiddle.net/buddhaspake/F6BE8/5

2. WORKAROUND using toggleClass() :
(As suggested by adeneo): to use jQuery toggleClass() method as per sample code in the link in adeneo's comment.

Try to use event-delegation since you are changing the class at run time,

$(document).on('click', '.class2', function() {

});

Side Note : I just delegated the event to the document, since I don't know about the static parent in your context, use a closest static parent to delegate the event. because if we rely upon the document then obviously it will be the last element while the event got bubbled up to the DOM tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM