首页 > 解决方案 > Dynamic hide/show divs after click on respective buttons with jQuery

问题描述

I have some divs that, when clicked, have to show other specific divs (with relative content) and hide all the others. I think it's a very simple request, but it gave me headache.

this is my code, hope that someone can help me:

$('.finiture-wrapper').on('click', function() {
        var idBtn = $(this).data('id');
        //console.log(idBtn);     
        if(idBtn == $('allestimento-img-wrapper').data('id')){
        $('allestimento-img-wrapper').css('display', 'flex')
        }
        else{
        $('allestimento-img-wrapper').css('display', 'none')
        }
        
    })        
.allestimento-img-wrapper{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="finiture-wrapper" data-id="silver-bagno-1">bagno 1</button>
<button class="finiture-wrapper" data-id="silver-bagno-2">bagno 2</button>
<button class="finiture-wrapper" data-id="silver-bagno-3">bagno 3</button>

<div class="allestimento-img-wrapper"  data-id="silver-bagno-1">content 1</div>
<div class="allestimento-img-wrapper" data-id="silver-bagno-2">content 2</div>
<div class="allestimento-img-wrapper" data-id="silver-bagno-3">content 3</div>

I've used data-id to connect the two divs but i can't properly show it. Plus, I'm trying to use if/else statement but maybe there is a smarter way.

Thank you. P.s. I'm super new to jquery, and this question may seems stupid.

标签: javascriptjqueryhtmlshow-hide

解决方案


$('.finiture-wrapper').on('click', function() {
        var idBtn = $(this).data('id');

        if(idBtn === $('allestimento-img-wrapper').data('id')){
         $('.allestimento-img-wrapper').css('display', 'flex')
         $('.allestimento-img-wrapper').data('id');
        }
        if(if(idBtn !== $('allestimento-img-wrapper').data('id')){
         $('.allestimento-img-wrapper').css('display', 'none');
        }
       })

我认为你忘记了 jQuery 中的 (.) 点。希望它能解决问题。


推荐阅读