如何通过for循环批量生成带递增图片名的重复div结构
Got it covered—you can use vanilla JavaScript to loop and generate those divs dynamically, so you don’t have to write the same repetitive code manually. Here’s a straightforward solution:
Step 1: Add a Container for Your Gallery
First, drop an empty container in your HTML where all the generated divs will live:
<div id="gallery-container"></div>
Step 2: Use a For Loop to Generate Divs
This code will create n copies of your target div, swapping out the image filename numbers with the current loop index. Just adjust the totalItems variable to match how many divs you need:
// Grab the container where we'll inject our divs const galleryContainer = document.getElementById('gallery-container'); // Set how many div instances you want to generate const totalItems = 5; // Update this to your desired count for (let i = 1; i <= totalItems; i++) { // Build the HTML string with incrementing numbers using template literals const galleryItem = ` <div class="isotope-item size3 col-lg-4 col-md-4 col-sm-12 col-xs-12 white-coat-talent all"> <div class="pm-gallery-post-item-container" style="background-image:url(img/gallery/2nd-white-coat${i}.jpg);"> <div class="pm-gallery-post-item-info-container"> <div class="pm-gallery-item-excerpt"> <p>LPSA hosted a talent show “White Coat Talent”, showcasing the talents of pharmacy students from all over Lebanon at Saint Joseph University.</p> <ul class="pm-gallery-item-btns"> <li><a class="fa fa-camera lightbox" data-rel="prettyPhoto[white-coat-talent]" href="img/gallery/white-coat-talent${i}.jpg"></a></li> <li><a class="fa-bars" href="#"></a></li> </ul> </div> </div> <a class="pm-gallery-item-expander fa fa-plus" href="#"></a> </div> <div class="pm-gallery-item-title"> <p>White Coat Talent</p> </div> </div> `; // Append each generated div to the container galleryContainer.innerHTML += galleryItem; }
Quick Adjustment for the Lightbox Image
In your original example, the lightbox link uses white-coat-talent11.jpg—if you meant this number to start at 11 and increment (11,12,13...), just replace ${i} in that href with ${10 + i}. Like this:
href="img/gallery/white-coat-talent${10 + i}.jpg"
How This Works
- The loop runs from 1 to
totalItems, so each iteration uses a unique number for the image filenames. - Template literals (backticks
`) make it easy to plug theivariable directly into the HTML string without messy concatenation. - Each generated div gets added to the
gallery-container, so they’ll render automatically on your page.
Important Checks
- Ensure your image files are named correctly (e.g.,
2nd-white-coat1.jpg,2nd-white-coat2.jpg) and stored in theimg/gallery/folder. - Tweak
totalItemsto match exactly how many divs you need. - If you want to adjust other dynamic content (like excerpt text or button links), you can add more variables to the loop just like we did with
i.
内容的提问来源于stack exchange,提问作者Wael Aboul Hosn

