简体   繁体   中英

How can I loop through an array of divs to show() them?

first post.. experienced with programming but not so much jQuery/javascript. I have some divs that are hidden at first, and they are assigned id's in ascending order:

  <script>
    $(document).ready(function() {
      $(".over_map").each(function(i) {
          $(this).attr('id', "over_map" + (i + 1));
          // console.log($(this));
      });
    });
  </script>

Now I want to loop through a dynamic number of these divs and show them. If (eventually, not implemented yet) an SQL call returns 4 records, I would want to show() 4 of the hidden divs. Seems like this should be simple but I am missing something.. limited internet access unfortunately, but I didn't find any stack overflow entries pertaining to it.. any help appreciated!

If you have a set of elements in a jQuery object, you don't need to loop them at all - just call .show() on the set.

eg

$('#over_map1, #over_map3').show();

If you have a list of ids that you want to show, you can build the selector string:

function buildSelector(ids) {
  var selectors = [];
  for (var i = 0; i < ids.length; i++) {
    selectors.push("#over-map" + ids[i]);
  }
  return selectors.join(", ");
}

$(document).ready(function(){
  var ids = [1, 3];
  $(buildSelector(ids)).show();
});

Demo at http://codepen.io/precise54/pen/nkyzg

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