繁体   English   中英

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

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

我在jquery中有addClass()removeClass()函数的问题。 当我使用该功能时,它是替换类。 但是它没有调用添加的类函数。 这是我的查询

HTML代码:

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

jQuery的:

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

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

我的添加和删除类函数是

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

如果单击animation1 ,它将调用ajax函数,它将类名替换为animation2并且它具有一些单独的函数。 怎么办呢? 请有人提出解决方案。

提前致谢,

当你写

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

jQuery使用此类找到元素,并向其添加clickhandler。 该函数未绑定到CSS类。

我建议您在ajax响应中添加clickhandler ,或者有2个按钮可以隐藏/显示

尝试通过文档添加事件处理程序:

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

问题是您的ajax没有返回成功,请检查控制台日志。 实际上问题不在于addClass和removeClass。 请参阅下面的示例。

在此示例中,当您单击文本单击我时 ,它将调用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