如何在点击var ID时添加/删除子元素类?

时间:2014-10-06 20:13:25

标签: javascript jquery

我有一支手风琴我正在使用FAQ页面。单击特定问题时,部分箭头需要从右向下更改。所有其他人需要默认回到右边。为了让这个工作,我错过了什么?

            <dd id="1" class="accordion-navigation">
                <i class="fa fa-chevron-right"></i> <a class="faq-toggle" href="#faq1">How can I plan my Wedding at Mayan Resorts?</a>
                <div id="faq1" class="content">
                  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
                </div>
            </dd>

            <dd id="2" class="accordion-navigation">
                <i class="fa fa-chevron-right"></i> <a class="faq-toggle" href="#faq2">Do you offer a service to plan the event start to finish?</a>
                <div id="faq2" class="content">
                  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
                </div>
            </dd>



$('.accordion-navigation').click(function() {
        var id = $(this).attr('id');

                if ($(id).hasClass('active')) {
                        $(id).find('i').removeClass('fa-chevron-right');
                        $(id).find('i').addClass('fa-chevron-down');
                }
                else if (!($('.accordion-navigation').hasClass('active'))) {
                        $('.accordion-navigation').find('i').addClass('fa-chevron-right');
                        $('.accordion-navigation').find('i').removeClass('fa-chevron-down');
                }
});

2 个答案:

答案 0 :(得分:1)

使用您的thistoggleClass的实例,您应该可以在几行内完成此操作:

$('.accordion-navigation').click(function() { 
    //Remove from all
    $('.accordion-navigation i').removeClass("fa-chevron-down").addClass("fa-chevron-right");    

    //Add to current
    $("i", this).toggleClass("fa-chevron-right fa-chevron-down");
});

答案 1 :(得分:0)

不知道为什么它不起作用,但我编写了自己的解决方案 - CSS和JS组合

http://jsfiddle.net/95rzLepo/

$(document).on('click', '.faq-toggle' ,function (e) {
    if($(this).prev().hasClass('fa-chevron-down')) {
        $(this).prev().removeClass('fa-chevron-down');
        $(this).prev().addClass('fa-chevron-right');
    } else {
        $(this).parents('body').find('.fa.fa-chevron-down').each(function (e) {
            $(this).removeClass('fa-chevron-down');
            $(this).addClass('fa-chevron-right');
        });

        $(this).prev().removeClass('fa-chevron-right');
        $(this).prev().addClass('fa-chevron-down');
    }
});