You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图片画廊实现报错:Uncaught TypeError: Cannot read property 'src' of undefined

Hey there, let's dig into this issue you're facing with your image gallery. That "Cannot read property 'src' of undefined" error tells us that when you first click a thumbnail, the code is trying to access the src property of something that doesn't exist (aka undefined). Since your prev/next buttons work fine, the core navigation logic is solid—this is almost certainly a problem with how you're passing or initializing the selected image index when the new page first loads.

1. Check How You're Passing the Image Index to the New Page

First, let's look at your thumbnail click handler. When opening the new page, you're likely passing the image's index via a URL parameter (like image-viewer.html?index=2). Make sure:

  • You're passing a valid numeric index (not a string, and not an index that falls outside your images array bounds).
  • Here's a correct example of a click handler:
// Thumbnail click handler (on your gallery page)
document.querySelectorAll('.thumbnail').forEach((thumb, index) => {
  thumb.addEventListener('click', () => {
    // Pass the numeric index in the URL
    window.open(`image-viewer.html?index=${index}`, '_blank');
  });
});
2. Fix Index Parsing on the Image Viewer Page

On the full-image page, common mistakes happen when reading the URL parameter. For example, forgetting to convert the string parameter to a number, or not validating if the index is valid. Here's a robust way to handle this:

// On your image viewer page
const urlParams = new URLSearchParams(window.location.search);
let currentIndex = parseInt(urlParams.get('index'), 10);

// Get your JSON image data array
const images = /* Your loaded image JSON array */;

// Validate the index to avoid out-of-bounds errors
if (isNaN(currentIndex) || currentIndex < 0 || currentIndex >= images.length) {
  // Fallback to the first image if the index is invalid
  currentIndex = 0;
}

// Function to load the selected image
function loadImage(index) {
  const fullImageElement = document.getElementById('full-image');
  fullImageElement.src = images[index].src; // No more undefined here!
}

// Load the initial image when the page loads
loadImage(currentIndex);
3. Ensure Your Image JSON is Fully Loaded Before Accessing It

If you're fetching the JSON data asynchronously (like with fetch()), there's a chance the viewer page tries to access the images array before it finishes loading. Wrap your index logic inside the async callback to fix this:

// On image viewer page - for async JSON loading
fetch('your-image-data.json')
  .then(response => response.json())
  .then(images => {
    const urlParams = new URLSearchParams(window.location.search);
    let currentIndex = parseInt(urlParams.get('index'), 10);
    
    // Validate index
    if (isNaN(currentIndex) || currentIndex < 0 || currentIndex >= images.length) {
      currentIndex = 0;
    }

    // Load initial image
    loadImage(currentIndex);

    // Set up prev/next buttons with the loaded images array
    document.getElementById('prev-btn').addEventListener('click', () => {
      currentIndex = (currentIndex - 1 + images.length) % images.length;
      loadImage(currentIndex);
    });

    document.getElementById('next-btn').addEventListener('click', () => {
      currentIndex = (currentIndex + 1) % images.length;
      loadImage(currentIndex);
    });
  });
4. Double-Check Thumbnail-Array Index Alignment

If you're generating thumbnails dynamically from the JSON, make sure the loop index matches the image's position in the array. For example:

// Generating thumbnails from JSON (gallery page)
images.forEach((image, index) => {
  const thumb = document.createElement('img');
  thumb.className = 'thumbnail';
  thumb.src = image.thumbnailSrc; // Use the thumbnail URL from your JSON
  thumb.dataset.index = index; // Optional: store index in a data attribute for clarity
  document.getElementById('gallery-container').appendChild(thumb);
});

Quick Debugging Test

If you're still stuck, add console logs to track the index value:

  • On the gallery page: console.log('Clicked thumbnail index:', index); when a thumbnail is clicked
  • On the viewer page: console.log('Parsed index:', currentIndex, 'Total images:', images.length);
    This will immediately show you if the index is invalid or out of bounds.

内容的提问来源于stack exchange,提问作者Hana Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 06:23:27