循环中根据变量值修改img src的问题排查
Hey there! Let's figure out why your image src updates aren't working while the Bootstrap carousel text is functioning perfectly. Based on your description, here are the most likely issues and fixes to try:
The most common culprit here is a miswritten selector that fails to target the correct <img> element. For example, if your images use a data attribute to match the integer value from your JSON, you need to format the selector properly.
Let's say your HTML has images like this:
<img data-slide-number="1" src="" class="d-block w-100" alt="Slide 1">
Your jQuery should use a selector that matches that data attribute correctly:
$.getJSON('your-data.json', function(data) { $.each(data.items, function(index, item) { // Target the img with data-slide-number matching the item's integer value const targetImage = $('img[data-slide-number="' + item.intValue + '"]'); // First confirm the element exists (critical for debugging!) if (targetImage.length) { targetImage.attr('src', `path/to/your/image-${item.intValue}.png`); } else { console.log(`No image found for value: ${item.intValue}`); } }); });
If targetImage.length returns 0, your selector is wrong—tweak it to match how your images are marked up.
Make sure your getJSON code runs after the DOM is fully loaded. If you're executing the script before the carousel images exist in the DOM, the selector won't find anything. Wrap your code in $(document).ready() to avoid this:
$(document).ready(function() { // Your getJSON and each loop code here });
If your carousel items are dynamically generated from the same JSON (you mentioned text works, but just in case), ensure you update the image src after you've added the carousel items to the DOM.
Double-check that the integer value in your JSON is actually a number (or that your selector accounts for strings). For example, if your JSON has "intValue": "3" instead of "intValue": 3, your selector still works as long as you're wrapping the value in quotes—but it's good to confirm with console.log(item.intValue) to see what data type you're working with.
Even if the selector works, a wrong file path will break the image. After setting the src, log the path to verify it's correct:
console.log(targetImage.attr('src'));
Check for typos, relative path issues (e.g., using images/slide.jpg instead of ./images/slide.jpg), or case sensitivity (some servers care if Slide.jpg vs slide.jpg).
If your images are inside inactive carousel items, some browsers might delay loading them—but the src should still be updated in the DOM. Use your browser's DevTools (Elements tab) to inspect the image element and confirm if the src attribute was actually changed, even if the image isn't visible yet.
Also, add a fail callback to your getJSON call to catch if the JSON file itself isn't loading:
$.getJSON('your-data.json', function(data) { // Your loop code }).fail(function(jqXHR, textStatus, errorThrown) { console.error('Failed to load JSON:', textStatus, errorThrown); });
Here's a full working example tying it all together:
<!-- Bootstrap Carousel HTML --> <div id="carouselExample" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img data-slide-number="1" src="" class="d-block w-100" alt="Slide 1"> <div class="carousel-caption"> <h5></h5> </div> </div> <!-- Repeat for slides 2-10 --> </div> </div> <script> $(document).ready(function() { $.getJSON('slides-data.json', function(response) { $.each(response.items, function(i, item) { // Update image const $img = $('img[data-slide-number="' + item.intValue + '"]'); if ($img.length) { $img.attr('src', `assets/slide-${item.intValue}.jpg`); // Update text (you said this works, just included for context) $img.closest('.carousel-item').find('h5').text(item.text); } else { console.warn(`No image found for slide number: ${item.intValue}`); } }); }).fail(function(jqXHR, textStatus) { console.error('JSON load failed:', textStatus); }); }); </script>
内容的提问来源于stack exchange,提问作者Gaurav Aggarwal

