dsfhd78978 2015-05-18 13:42
浏览 103
已采纳

jquery为这个被点击的元素添加类

I generate several rows <tr> with tasks. Now, each task can be marked as complete by clicking on a span. I do that with an ajax request.

Here's the html:

<table>
    <tr>
        <td>#1</td>
        <td><span class="icon-complete-a to-heal"></span></td>
    </tr>
    <tr>
        <td>#2</td>
        <td><span class="icon-complete-a to-heal"></span></td>
    </tr>
    <tr>
        <td>#3</td>
        <td><span class="icon-complete-a to-heam"></span></td>
    </tr>
</table>

Now when I click on a certain span element, only that element should change class.

I use this to change class:

$(".to-heal").addClass("completed-task");

But all my span elements are getting the completed class.

So I tried with the following:

$(this).find(".to-heal").addClass("completed-task");

But that doesn't work.

Any help?

UPDATE

I tried using the $(this).addClass("completed-task");

Here is the full ajax request I'm using:

$(".to-heal").click(function() {

    var task = $(this).attr("data-task");

    $.ajax({

        type: "post",
        url: "assets/js/ajax/mark-as-complete.php",
        data: { 'task': task },
        success: function() {

            $(this).addClass("completed-task");

            $(".completed-task").click(function() {

                var task = $(this).attr("data-task");

                $.ajax({

                    type: "post",
                    url: "assets/js/ajax/mark-as-incomplete.php",
                    data: { 'task': task },
                    success: function() {

                        $(this).removeClass("completed-task");

                    }

                });

            });

        }

    });

});

The markup classes are not the same anymore, as I used dummy classes for quick explanation. Sorry for that...

Thanks though

  • 写回答

4条回答 默认 最新

  • duancilan5124 2015-05-18 13:44
    关注

    The context of element is lost in ajax call. you can use context option in ajax to set any elements context:

    context:this,
    

    Ajax call snippet:

    $.ajax({
       type: "post",
       context:this,
       url: "assets/js/ajax/mark-as-incomplete.php",
       data: { 'task': task },
       success: function() {
           $(this).removeClass("completed-task");
       }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊