开发者

Trying to dynamically expand different divs with one function

I'm trying to be able to dynamically expand / collapse multiple divs with the same code....

it's controlled with the click of a span (toggle) and then i'm trying to get the next id(the div that would slide up and down)

            $('span').toggle(
    function() {
$('#albumholder').slideToggle(600);
    $(this).html('-');},
    function() {
$('#albumholder').slideToggle(600);
    $(this).html('+');}

    );

This code works to expand 1 div... but assume i have a divs

#downloadholder

#linksholder开发者_高级运维

etc...

How can i achieve the same effect with the same code? Thanks!

EDIT

It's worth noting that I need each div to toggle independently. If i click the plus button on the span that is affecting #albumholder, it should not expand #downloadholder or #linksholder


Two ways -

add them in the selector

$('#downloadholder, #linksholder') 

or add a class to those items

$('.toExpand')

<div id="downloadholder" class="toExpand" />
<div id="linksholder" class="toExpand" />

Rereading your question, it's perhaps you want to get the next div?

$('#yourSpanElement').click(function() {
    $span = $(this);
    $yourDiv = $span.next('div');
   // do your magic :)
});

your code revamped:

$('span').toggle(
    function() {
      var $span = $(this);
      $span.next('div').slideToggle(600);
      $span.html('-');
    },      
    function() {
      var $span = $(this);
      $span.next('div').slideToggle(600);
      $span.html('+');
    }
 );

you could also check for the next divs appearance:

$('span').click(function() {
  var $span = $(this);
  var $nextDiv = $span.next('div');
  if( $nextDiv.is(':visible') ) {
     $nextDiv.slideUp(600);
     $span.html('+');
  }else {
     $nextDiv.slideDown(600);
     $span.html('-');
  }
});


Make you htmlr something like this.

<span toggletarget="downloadholder>+</span>
<div id="downloadholder"></div>

Then make your javascript

$('span[toggletarget]').click(function () {$(this).toggle(
function() {
    $("#"+$(this).attr("toggletarget")).slideToggle(600);
    $(this).html('-');},
function() {
$('#albumholder').slideToggle(600);
$(this).html('+');}
);});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜