简体   繁体   中英

how to only show specific element when another is clicked

I have a set of tabs that will each contain there own set of questions with each question having a specific answer.

The tab structure is sound and exactly how I wanted it to be when built. My problem lies with the questions and answers themselves.

The desired functionality is when a question is clicked the answer for that question should be shown. I have a simple grasp of it here with this JSFiddle but I am struggling on how to differentiate between what question is being clicked and therefore which answer to show.

Basic understanding of whats needed:

$('.question-text').click(function(){
   $(".answer-text").toggleClass("hidden");
});

I saw this fiddle that uses jquery's closest but cant figure out how to convert that to my particular code. Here is what I have tried with no avail:

$(".question").each(function(){
    $('.question-text').click(function(){
         var $par=$(this).closest('.answer')
         $par.find(".answer-text").slideDown("1000");
     });
})

Any help on this would be greatly appreciated!

You can remove iterating question.each and simply bind click on all the question-text.

When the question-text is clicked , grab the next sibling which is your answer.

$('.question-text').click(function(){
         var $par=$(this).next()
         $par.find(".answer-text").toggleClass("hidden");
     });
})

You can do it using parent() in your jquery, i think it is similar as FAQ question and answers view. try the below code by replacing your class names.

<script>

$(document).ready(function() {

$('.faq_question').click(function() {

    if ($(this).parent().is('.open')){
        $(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500);
        $(this).closest('.faq').removeClass('open');

        }else{
            var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px';
            $(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500);
            $(this).closest('.faq').addClass('open');
        }

});

});

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