weixin_33724659 2014-09-16 21:09 采纳率: 0%
浏览 13

成功添加课程

I'm looking to add a class on the element that is clicked on after POST was successful. For some reason, neither "this" nor "'add_favorite',this" is adding "favorited". Everything else works just fine.

Any ideas?

 $('.add_favorite').click(function(){
    expert_id = $(this).attr('data-expert-id');
    user_id = $(document.body).attr('data-user-id');

    //console.log(user_id);

    var data = {
        'expert_id' : expert_id,
        'user_id' : user_id
    }

    var url = "/submit-fav.php";

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function(data)
        {
            $(this).addClass('favorited');
        }
    });

    return false;
 });
  • 写回答

1条回答 默认 最新

  • perhaps? 2014-09-16 21:11
    关注

    You need to keep a local copy of the original "this" in order to access it from within the scope of the success callback (which has a different "this").

     $('.add_favorite').click(function(){
        var  $add_favorite = $(this);
        var expert_id = $add_favorite.attr('data-expert-id');
        var user_id = $(document.body).attr('data-user-id');
    
        //console.log(user_id);
    
        var data = {
            'expert_id' : expert_id,
            'user_id' : user_id
        }
    
        var url = "/submit-fav.php";
    
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            success: function(data)
            {
                $add_favorite.addClass('favorited');
            }
        });
    
        return false;
     });
    

    Notes:

    • I tend to prefix jQuery object variables with $
    • Your should declare all your local variables with var or they modify/pollute the global namespace.
    评论

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算