jQuery add/remove class using 'this'

jQuery add/remove class using 'this'

本文关键字:this using class add remove jQuery      更新时间:2023-09-26

我试图在div点击时将一个类附加到它,并在它第二次点击时删除它。我现在有我的脚本-

    $(".project").click(function(){
        if ($(".project-expand", this).is(':visible')) {
            $(".project-expand",this).hide(1000);
            $('.project').delay(1000).queue(function(){
            $(".project").removeClass('item-dropped').clearQueue();
          });
        } else if ($(".project-expand", this).is(':hidden')) {
            $(".project-expand").hide(1000);
            $(".project-expand",this).show(1000);
            $(".project").addClass('item-dropped');
        }
    });

但是,当我将代码更改为-时,这会将"item droped"类添加到所有具有类"project"的div中

$(".project", this).addClass('item-dropped');

它什么都没用,我哪里错了?

不用类选择器$('.project'),只需使用点击事件的目标($(this)):

$(".project").click(function () {
    var project = $(this);
    var projectExpand = $(".project-expand", this);
    if (projectExpand.is(':visible')) {
        projectExpand.hide(1000);
        project.delay(1000).queue(function () {
            project.removeClass('item-dropped').clearQueue();
        });
    } else if (projectExpand.is(':hidden')) {
        $(".project-expand").hide(1000);
        projectExpand.show(1000);
        project.addClass('item-dropped');
    }
});

其他信息:您尝试执行的操作最初不起作用的原因是,$('.project', this)在当前元素中查找类为project的元素(即在项目中查找项目)

您必须使用$(this)在单击的项目上添加类:

        $(".project").click(function(){
            if ($(".project-expand", this).is(':visible')) {
                $(".project-expand",this).hide(1000);
                $(this).delay(1000).queue(function(){
                $(this).removeClass('item-dropped').clearQueue(); // Here
              });
            } else if ($(".project-expand", this).is(':hidden')) {
                $(".project-expand").hide(1000);
                $(".project-expand",this).show(1000);
                $(this).addClass('item-dropped'); // Here
            }
        });

您必须使用:

$(this).addClass('item-dropped');

概念小提琴