문제

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');
});
도움이 되었습니까?

해결책

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

다른 팁

Use $(document).on

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

DEMO

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/

See here

 $(document).on('click','.item:not(.active)', function(){
   $('<p>Not active</p>').appendTo('body');
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top