簡體   English   中英

如何在jQuery中添加狀態onClick?

[英]How to add states onClick in jQuery?

我有以下代碼添加和刪除一個類。 但是我想在圖像處於活動狀態時在其上添加另一個類,而在非活動狀態時將其刪除。 問題是我可以添加,但不僅對於打開一個元素,所有元素都將處於活動狀態。 有誰知道如何解決這個問題?

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();
});
});

更新:

 $(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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM