将添加/删除类隔离到单击的项目

时间:2015-05-21 18:44:04

标签: javascript jquery addclass removeclass toggleclass

目前我有一个手风琴菜单,每次点击.responsive-accordion-head我告诉它按如下方式切换课程:

$('.responsive-accordion-head').click(function () {

    if ( $( '.responsive-accordion-head i' ).hasClass( "plus-2" ) ) {

        $('.responsive-accordion-head i').removeClass("plus-2");
        $('.responsive-accordion-head i').addClass("minus-2");

    } else {
        $('.responsive-accordion-head i').removeClass("minus-2");
        $('.responsive-accordion-head i').addClass("plus-2");
    }

});

我遇到的问题是上面的代码更改了所有.responsive-accordion-head元素的类。我需要它仅针对所点击的项目。我该怎么做?

1 个答案:

答案 0 :(得分:5)

所有这一切都可以简化为:

$('.responsive-accordion-head').click(function () {
    $(this).find('i').toggleClass('plus-2 minus-2');
});