无法通过jQuery/JS获取JSP页面产品图片数组,求解决方案
Hey Elena, let's fix this image carousel issue step by step. The main problems with your current code are duplicate IDs (which break DOM selection) and a global count variable that will cause conflicts when you have multiple product containers. Here's how to resolve it:
Step 1: Fix Duplicate IDs in JSP
IDs must be unique across the entire DOM, so replace all repeated IDs with classes, and adjust the button click handlers to pass context about which product container they belong to:
<c:forEach items="${produkt}" var="produkt"> <div class="produkt-container" style="border: 1px solid #ccc; display: inline-block; text-align:left;" data-current-index="0"> <a href="produkt${produkt.id}">${produkt.model}</a> <div class="img-container" style="max-width: 280px"> <button class="btnClass prev-btn" onclick="plusImg(this, -1)">❮</button> <c:forEach items="${produkt.images}" var="image"> <img src="${image}" class="img-item" alt="" style="border: 1px solid black; width: 260px; display: none;"> </c:forEach> <button class="btnClass next-btn" onclick="plusImg(this, 1)">❯</button> </div> </div> </c:forEach>
Key changes here:
- Replaced duplicate IDs like
img-container,prev,next,img-listwith unique classes - Added
display: noneto images to hide them by default - Added
data-current-index="0"to each product container to track its active image index independently - Updated
onclickhandlers to pass the button element itself and the step value
Step 2: Rewrite JavaScript to Work with Per-Product Context
Adjust your JS to target the specific product container tied to the clicked button, avoiding global variable conflicts:
<script> // Initialize carousels when the page finishes loading document.addEventListener('DOMContentLoaded', function() { const productContainers = document.querySelectorAll('.produkt-container'); productContainers.forEach(container => { const firstImg = container.querySelector('.img-item'); if (firstImg) { firstImg.style.display = 'block'; container.dataset.currentIndex = '0'; } }); }); function plusImg(button, step) { // Get the parent product container of the clicked button const productContainer = button.closest('.produkt-container'); const imgs = productContainer.querySelectorAll('.img-item'); const totalImgs = imgs.length; if (totalImgs === 0) return; // Fetch and update the current index from the container's data attribute let currentIndex = parseInt(productContainer.dataset.currentIndex); currentIndex += step; // Wrap around index if it goes out of bounds if (currentIndex >= totalImgs) { currentIndex = 0; } else if (currentIndex < 0) { currentIndex = totalImgs - 1; } // Hide all images, then show the active one imgs.forEach(img => img.style.display = 'none'); imgs[currentIndex].style.display = 'block'; // Save the updated index back to the container productContainer.dataset.currentIndex = currentIndex.toString(); } </script>
Key improvements here:
- Uses
DOMContentLoadedto initialize carousels properly after the page renders - Uses
button.closest('.produkt-container')to target only the images in the clicked product's container - Stores the active index in a
data-*attribute per product, so carousels don't interfere with each other - Handles index wrapping (loop from last image to first, and vice versa)
- Fixes the incorrect class selection syntax from your original code
Why Your Original Code Failed
- Duplicate IDs: When looping with
<c:forEach>, you created multiple elements with the same ID. The DOM only recognizes the first element with a given ID, leading tonullreturns or incorrect selections. - Global
countVariable: A single global count would be shared across all carousels, meaning clicking next on one product would affect every other product's carousel. - Incorrect Selection:
document.getElementsByClassName(".img-list")included an extra dot (class names don't require the dot in this method), and it selected all images on the page instead of just the ones in the target product.
This solution will give you independent, working carousels for each product in your list.
内容的提问来源于stack exchange,提问作者Elena Zhul

