jquery为这个被点击的元素添加类 [英] jquery add class to this clicked element

查看:87
本文介绍了jquery为这个被点击的元素添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用任务生成了几行< tr> 。现在,通过单击 span ,可以将每个任务标记为完成。我用ajax请求这样做。

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.

这是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>

现在当我点击某个span元素时,只有那个元素应该改变类。

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

我用它来改变类:

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

但我所有的span元素都是完成的课程。

But all my span elements are getting the completed class.

所以我尝试了以下内容:

So I tried with the following:

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

但这不起作用。

任何帮助?

更新

我尝试使用 $(this).addClass(completed-task);

这是我正在使用的完整ajax请求:

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...

非常感谢

推荐答案

背景在ajax调用中丢失了元素。您可以在ajax中使用 context 选项来设置任何元素上下文:

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 call snippet:

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

这篇关于jquery为这个被点击的元素添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆