简体   繁体   中英

JQuery Click on :not() Selected Element Only Firing Once

http://jsfiddle.net/qLhp7mns/1/

Hi there! I've got a bit of a problem with this simple toggle - I'm unable to toggle it back to its original state after one .click event! I have no clue what I'm doing wrong (or at all, for that matter). The Javascript console in-browser shows no errors, so I'm even more confused!

I've been browsing the many questions from those with the same problem, but adding the "on" event seems to do nothing (unless I'm doing that incorrectly too!). Hopefully this isn't just more of the same :c Thanks in advance! <3

Here's the line of JQuery that's causing the trouble:

$('.tog:not(.selected)').click(function(){
$('.tog.selected').removeClass('selected');$(this).addClass('selected');
});

Try this instead ( fiddle )

$(document).on('click', '.tog:not(.selected)', function() {
   $('.tog.selected').toggleClass('selected');
   $(this).toggleClass('selected');
});

When using toggleClass() , it's possible to simplify it to

 $(document).on('click', '.tog:not(.selected)', function () {
    $('.tog').toggleClass('selected');
 });

which toggles the class selected for both divs with the class tog . Fiddle

As you mentioned you tried using on() without getting the wanted result and maybe having used it wrong, an explanation - events like click() can only be applied to elements actually being in the DOM when the page is loaded. To apply event handlers to elements that are added later or are eg the result of adding a class, event delegation can be used - a static parent element, eg $(document) - delegates the event to the dynamically added / adjusted element.

For reference: https://api.jquery.com/on/#on-events-selector-data-handler , section "Direct and delegated events":

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

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