简体   繁体   English

removeclass()和addClass()无法使用ajax

[英]removeclass() and addClass() not working using ajax

I am having problem with addClass() and removeClass() function in jquery. 我在jquery中有addClass()removeClass()函数的问题。 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 : HTML代码:

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

Jquery : 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. 如果单击animation1 ,它将调用ajax函数,它将类名替换为animation2并且它具有一些单独的函数。 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. jQuery使用此类找到元素,并向其添加clickhandler。 The function is not bound to the css-class. 该函数未绑定到CSS类。

I would suggest you either add a clickhandler in your ajax response , or have 2 buttons which you can hide / and show 我建议您在ajax响应中添加clickhandler ,或者有2个按钮可以隐藏/显示

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. 问题是您的ajax没有返回成功,请检查控制台日志。 actually problem was not with addClass and removeClass. 实际上问题不在于addClass和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 在此示例中,当您单击文本单击我时 ,它将调用ajax请求,而ajax将导致错误,因此执行错误代码

 $(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM