简体   繁体   中英

Lots of identical buttons and (collapsed) divs on the same page. How do I use Jquery so that each button expands the appropriate div?

html:

<button class='expandotron'></button>
<div class='detail-view'></div>
<button class='expandotron'></button>
<div class='detail-view'></div>
<button class='expand'></button>
<div class='detail-view'></div>

the jquery:

$('.expandotron').click(function() {
    if($( ".detail-view" ).css('display') != 'none'){
         $( ".detail-view" ).css('display', 'none');
         $( ".fixed-table-body" ).css('height', '0px'); // ignore this line
         $( ".table-pad ").css('padding', '0px'); // ignore this line
      } else {
         $( ".detail-view" ).css('display', 'table-row');
         $( ".fixed-table-body" ).css('height', 'auto'); //ignore this line
         $( ".table-pad" ).css('padding', '12px'); // ignore this line
      }

This just links all of the buttons to all of the divs

You can use the jQuery next selector to find the next element that matches a certain criteria. For instance, to get the next div with the class detail-view you can use $(this).next( ".detail-view" ) and so on inside of your click event, so that your final jQuery code would look something like:

$('.expandotron').click(function() {
    if($(this).next( ".detail-view" ).css('display') != 'none'){
         $(this).next( ".detail-view" ).css('display', 'none');
         $(this).next( ".fixed-table-body" ).css('height', '0px');
         $(this).next( ".table-pad ").css('padding', '0px');
      } else {
         $(this).next( ".detail-view" ).css('display', 'table-row');
         $(this).next( ".fixed-table-body" ).css('height', 'auto');
         $(this).next( ".table-pad" ).css('padding', '12px');
      }
});

Thank you for your input, guys :) I ended up using this:

 $( ".expandotron" ).each(function( index, element ) {

       $(element).click(function(){
           if( $( ".detail-view:eq("+String(index)+")" ).css('display') == 'none'){
            $( ".detail-view:eq("+String(index)+")" ).css('display', 'table-row');
            $( ".fixed-table-body:eq("+String(index)+")").css('height', 'auto');
            $( ".table-pad:eq("+String(index)+")" ).css('padding', '12px');
        } else {
            $( ".detail-view:eq("+String(index)+")" ).css('display', 'none');
            $( ".fixed-table-body:eq("+String(index)+")").css('height', '0');
            $( ".table-pad:eq("+String(index)+")" ).css('padding', '0px');
        }
      }); 

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM