jQuery Show and Hide multiple divs with a selected class

有些话、适合烂在心里 提交于 2019-12-07 01:02:26

问题


I need to be able to show and hide divs based on which href class is 'selected' I have some code below:

http://jsfiddle.net/XwN2L/722/

I need to remove the 'all' option in the fiddle above.

So basically when a href has the class of selected the two links for the href are shown, then when a user clicks on another href, it hides the previous links and shows the new links with the class 'selected'

When they click on the link the selected class changes and the buttons hide and show accordingly?

Nearly there just need help on the last bits.

<div class="buttons">
 <a id="showall">All</a>
 <a class="showSingle" target="1">Div 1</a>
 <a class="showSingle selected" target="2">Div 2</a>
 <a class="showSingle" target="3">Div 3</a>
 <a class="showSingle" target="4">Div 4</a>
</div>

<div id="div1" class="targetDiv">
 <a href="#" class="button3">1a</a>
 <a href="#" class="button3">1b</a>
</div>

<div id="div2" class="targetDiv">
 <a href="#" class="button3">2a</a>
 <a href="#" class="button3">2b</a>
</div>

<div id="div3" class="targetDiv">
  <a href="#" class="button3">3a</a>
  <a href="#" class="button3">3b</a>
</div>

<div id="div4" class="targetDiv">popup COMPLETE</div>

<script>
 jQuery(function(){
    jQuery('.showSingle').click(function(){
          jQuery('.targetDiv').hide();
          jQuery('#div'+$(this).attr('target')).show();
     });
 });​
<script>

Cheers


回答1:


You can use data-* attributes:

<div class="buttons">
  <a  id="showall" data-target="all" >All</a>
  <a  class="showSingle" data-target="1">Div 1</a>
  <a  class="showSingle selected" data-target="2">Div 2</a>
  <a  class="showSingle" data-target="3">Div 3</a>
  <a  class="showSingle" data-target="4">Div 4</a>
</div>

var $target = $('.targetDiv'); // caching object for better performance

$('.buttons a').click(function(e) {
    e.preventDefault();
    $(this).addClass('selected').siblings().removeClass('selected');
    var target = $(this).data('target');
    if (target === 'all') {
        $target.show();
    } else {
        $target.hide().filter('#div' + target).show();
    }
});

http://jsfiddle.net/fKHsB/



来源:https://stackoverflow.com/questions/13140017/jquery-show-and-hide-multiple-divs-with-a-selected-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!