You can use .live() to do what you want, for example:
$(function() { $("img.off").live('click', function() { alert('on'); $(this).attr('class', 'on'); }); $("img.on").live('click', function() { alert('off'); $(this).attr('class', 'off'); }); });
When you execute $(selector).click() , you find the elements that match at that time and attach the handler to the click event ... when their class changes later, it does not matter for this, the handler is attached. .live() works differently, actually taking care of choosing a selector when an event occurs .
Also, depending on your example / what you end up with after this, something like .toggleClass() might simplify it for you, for example:
$(function() { $("img.off, img.on").live('click', function() { $(this).toggleClass('on off'); alert($(this).attr('class')); }); });
Nick craver
source share