简体   繁体   中英

How to show/hide certain div when i have multiple div with same class name

I had multiple div with class name blueflip i want to toggle this class's div content when the div link_button is clicked.

My Code :

$(document).ready(function(){
   $('.blueflip').hide(); 
   $('.link_button').click(function() {
      $('.blueflip').toggle(400);
      return false;
   });
});

It works fine. But my problem is, my page has multiple link_button and blueflip div's all over the page. when i click any one of link_button all of the blueflip div's are toggling. But i need to toggle the corresponding child blueflip div only

Note : The divs are dynamically generated from database.

How to achieve that, Plz help. Any suggestion will be highly appreciated

This should do it, assuming that .blueflip is a child of .link_button :

$(document).ready(function(){
   $('.blueflip').hide(); 
   $('.link_button').click(function() {
      $(this).find('.blueflip').toggle(400);
      return false;
   });
});

This works because of jQuery's .find() method, which always searches for descendants of the selector indicated by the parent jQuery object.

If .blueflip nodes are not children of the corresponding .link_button nodes, you might need to introduce some trickery into your object IDs. If everything has a unique ID (even if it's just an increment counter when the DIVs are generated), and you can correspond .link_button IDs to .blueflip IDs (eg, div#lb_001 corresponds to div#bf_001 ), then this should work:

$(document).ready(function(){
   $('.blueflip').hide(); 
   $('.link_button').click(function() {
      $('#bf' + $(this).attr('id').substr(2)).toggle(400);
      return false;
   });
});

If yo know the structure of page you would have to walk thru the dom tree, looking for the required div (maybe based on how many div's so far counted).

http://www.quirksmode.org/dom/intro.html

http://www.howtocreate.co.uk/tutorials/javascript/dombasics

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