The click function still works for the previous class that has already been replaced with another one

I have a problem with jQuery click event. When I replace the class div

, the click function still works for the previous class. Here is the code I am working with:

$(this).removeClass('edit_agent_val').addClass('edit_agent_val2');

      

The click function still works for edit_agent_val

instead of edit_agent_val2

.

// This should not work
$('.edit_agent_val').on('click', function(e) {          
     // some code...
});

// This should work
$('.edit_agent_val2').on('click', function(e) { 
    // some code...
});

      

Can anyone help me fix this problem?

+3


source to share


2 answers


The problem is that events are bound to load when the element still has its original class. The act of changing a class attribute does not affect any events associated with the element.

To achieve what you want, you need to use a delegated event handler that is bound to the parent element:



$(document).on('click', '.edit_agent_val', function(e) {
     // some code...
});

$(document).on('click', '.edit_agent_val2', function(e) {
    // some code...
});

      

Please note that I've only used it here document

as an example. In the final working code, you should use the closest parent for both elements .edit_agent_val

.

+6


source


Use event delegation

to dynamically add and remove a class.

If Dom didn't know the class is being removed or not when traversing, so use document or immediate parent selector to traverse it again and check if the class was found or not



$(document/immediateParent).on('click', '.edit_agent_val' ,function(e){          **// This should not work**
     // some code...
});

$(document/immediateParent).on('click', '.edit_agent_val2', function(e){        **// This should work**
    // some code...
});

      

+2


source







All Articles