简体   繁体   中英

How to add states onClick in jQuery?

I have the following code which add and remove a class. But I want to add another class over the image when is active and remove it when is inactive. The problem is that I could added but is going to be active for all elements not only for the one is opened. Does anyone has an idea how to fix this?

https://jsfiddle.net/bmhv3edw/3/

$(document).ready(function() {
function close_answer_section() {
    $('.question-text').removeClass('active');
    $('.plus').attr("src","http://tdhtestserver.herobo.com/plus-eclipse.png");
    $('.answer-section-content').slideUp(300).removeClass('open');
}

$('.question-text').click(function(e) {
    var currentAttrValue = $(this).attr('href');
    if($(this).is('.active')) {
        close_answer_section();
    }else {
        close_answer_section();
        $(".plus").attr("src","http://tdhtestserver.herobo.com/plus-eclipse-active.png");
        $(this).addClass('active');
        $('.questions ' + currentAttrValue).slideDown(300).addClass('open'); 
    }

    e.preventDefault();
});
});

UPDATED:

 $(document).ready(function() { function close_answer_section() { $('.question-text').removeClass('active'); $('.plus').attr("src","http://tdhtestserver.herobo.com/plus-eclipse.png"); $('.answer-section-content').slideUp(300).removeClass('open'); } $('.question-text').click(function(e) { var currentAttrValue = $(this).attr('href'); if($(this).is('.active')) { close_answer_section(); }else { close_answer_section(); $(this).find('img').attr("src","http://tdhtestserver.herobo.com/plus-eclipse-active.png"); $(this).addClass("active"); $('.questions ' + currentAttrValue).slideDown(300).addClass('open'); } e.preventDefault(); }); }); 
 /* body{ background: black }; */ .questions{ padding-top: 25px; padding-left: 170px; padding-bottom: 25px; } .question{ padding: 5px; font-size: 18px; font-weight: 100; } .answer-section-content { display:none; padding: 2px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="questions"> <div class="question"> <div class="question-text" href="#answer-52"><img class="plus" src="http://tdhtestserver.herobo.com/plus-eclipse.png"/> Question 1</div> <div id="answer-52" class="answer-section-content"> <p>Answer 1</p> </div> </div> <div class="question"> <div class="question-text" href="#answer-53"><img class="plus" src="http://tdhtestserver.herobo.com/plus-eclipse.png"/> Question 2</div> <div id="answer-53" class="answer-section-content"> <p>Answer 1</p> </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM