简体   繁体   中英

removeclass() and addClass() not working using ajax

I am having problem with addClass() and removeClass() function in jquery. When i use the function it was replace the classes. but it was not calling the addded class functions. here is my query

HTML Code :

<div class="animation1 popbutton">Click Me</div>

Jquery :

$(".animation1").click(function(){ 
   // my first function 
 });

$(".animation2").click(function(){ 
   // my second function 
 });

and my add and remove class functions are,

$.ajax({
    url : 'file.php',
    data : postdata,
    type : 'post',
    success : function (saveresponseText)
    {
        $(".animation1").removeClass("animation1").addClass("animation2").html("Clicked");
    } 
});

if click the animation1 it will call the ajax function and it will replace the classname as animation2 and it has some separate function. how can do this? Someone suggest a solution please.

Thanks in Advance,

When you write

$(".animation1").click(function(){ 
   // my first function 
 });

jQuery find the element with this class and adds a clickhandler to it. The function is not bound to the css-class.

I would suggest you either add a clickhandler in your ajax response , or have 2 buttons which you can hide / and show

Try to add the event handler through document:

$(document).on('click','.animation2',function(){ 
   // my second function 
});

problem is that your ajax is not returning success check the console logs. actually problem was not with addClass and removeClass. see the example below.

in this example when you click on text click me it will call ajax request and ajax will result error so that code written in error is excecuted

 $(document).ready(function() { $(".animation1").click(function() { // my first function clk() }); $(".animation2").click(function() { // my second function }); function clk() { $.ajax({ url: 'file.php', type: 'post', success: function(saveresponseText) {}, error: function(status) { $(".animation1").removeClass("animation1").addClass("animation2").html("Clicked"); } }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="animation1 popbutton">Click Me</div> 

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