0

When I dynamically add a class to an element, pseudo filtering doesn't recognize that class. This problem occurs when I use on() function, but everything is fine when I use live()

http://jsfiddle.net/AHyyq/1/

At the beginning, all list items are clickable. But after you press the button, "Ipsum" should not be clickable any more, and should not appear another "Not active" message.

$('.item:not(.active)').on('click', function(){
   $('<p>Not active</p>').appendTo('body');
});

4 Answers4

3
$('body').on('click', '.item:not(.active)', function(){
    $('<p>Not active</p>').appendTo('body');
});
Vassilis
  • 2,801
  • 1
  • 20
  • 16
1

Use $(document).on

$(document).on('click','.item:not(.active)', function(){
   $('<p>Not active</p>').appendTo('body');
});

DEMO

Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
0

It is correct behavior. You are adding events to non active elements (all 3 .item's). So it will not unbind events if you add class.

I would do something like this:

$('input[type=button]').click(function(){
    $('.item:nth-child(2)').addClass('active').css('color','#F00');
});

$('.item').on('click', function() {    
    if($(this).is('.active')) return;

    $('<p>Not active</p>').appendTo('body');
});

http://jsfiddle.net/AHyyq/9/

inser
  • 1,190
  • 8
  • 17
-1

See here

 $(document).on('click','.item:not(.active)', function(){
   $('<p>Not active</p>').appendTo('body');
});
PSR
  • 39,804
  • 41
  • 111
  • 151