开发者

jQuery Toggle with multiple unique DIVs?

I am using jQuery toggle with a link and a div. I will eventually have approx. 50 divs i want to toggle, an开发者_如何转开发d instead of creating a new function for each one, is there a way i can create a class and have it read unique ID's for each div? (if that makes sense)

For instance, i will have A1, A2, A3, B1, B2, B3..e.tc..

  $(document).ready(function() {

  $('#slickbox').hide();


  $('a#slick-toggleA1').click(function() {
    $('#A1').toggle(300);
    return false;
  });



});


HTML

<a class="clicker" href="#box1">Box 1</a>

<div class="coolbox" id="box1">I'm hidden!</div>

JavaScript

$('.coolbox').hide();

$('.clicker').click(function(event){
    event.preventDefault();
    $($(this).attr('href')).toggle(300);
});


you can iterate through wrapped sets with .each():

$('div').each(function(i){
  $(this).toggle(300);

});

of course you can limit a wrapped set through a selector. Alternativly, cou can use .filter() on all divs to find those divs you want to toggle.


So lets add the class slick-toggle to your a tags. and lets change their id'to something more definitively parseable -slick-toggle-$ID` where $ID is the id of the div to toggle. then we do this in $.ready...

$('a.slick-toggle').click(function(){
   var divId = '#'+$(this).attr('id').split('-').pop();
   $(divId).toggle();
   return false;
});


you can use different selector for div's being toggeled. For instance class or custom attribute

$('.clicker').click(function(){
  $('[toggeled]').toggle(300);
  return false;
}

having in mind the following markup

<div class="clicker">Click Me</div>
<div id="first" toggled="true">First to hide</div>
<div id="second" toggled="true">second to hide</div>
<div id="third" toggled="true">third to hide</div>


If you give your links a class and used the href like this:

<a class="opener" href="#A1">Open A1</a>
<div id="A1">Content here</div>

With this jQuery:

$('a.opener').click(function() {
  $(this.href).toggle(300);
  return false;
});

If javascript was disabled, the anchors would still navigate to the divs on the page as well.


Give the link a class, and stick the id of the div you want to toggle in the "rel" attribute - that's even standards compliant.

Then your function can look like this:

$('a.specialClass').click(function(){
  $('#'+$(this).attr('rel')).toggle(300);
  return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜