How to show only the selected div [duplicate]

1

I have a list with 3 elements and 3 divs.

<ul>
    <li>Todos</li>
    <li>elemento 1</li>
    <li>elemento 2</li>
    <li>elemento 3</li>
</ul>

<div id="1">elemento 1</div>
<div id="2">elemento 2</div>
<div id="3">elemento 3</div>

What I'm trying to do is click on an element in the list and show the corresponding div and hide the other divs. Can anyone show me some ways on how to do this with jquery?

    
asked by anonymous 12.01.2015 / 15:07

1 answer

3

See if this works for you:

$(function() {
    $('ul#items li').click(function(){
        var item = $('.elem[data-item="' + $(this).attr('data-item') + '"]');
        if($(this).attr('data-item') == 'all') {
            $('div.elem').show();
            return;
        }
        item.show();                                     
        $('div.elem[data-item!="'+item.attr('data-item')+'"]').hide();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="items">
    <li data-item="1">elemento 1</li>
    <li data-item="2">elemento 2</li>
    <li data-item="3">elemento 3</li>
    <li data-item="all">Todos</li>
</ul>

<div data-item="1" class="elem">elemento 1</div>
<div data-item="2" class="elem">elemento 2</div>
<div data-item="3" class="elem">elemento 3</div>

Elements are associated with the data-item attribute, that is, the li where the value of the data-item attribute is 3 will show the div with data-item 3 and hide the others. The element with data-item equal to all will show all divs again.

If you want the others to be hidden by default, just add display: none to the css.

    
12.01.2015 / 15:23