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

如何用JavaScript获取图片alt标签?Flickity轮播代码调试求助

Got it, let's fix this alt tag issue for your Flickity carousel! The problem here is pretty straightforward once you break down what's happening.

What's Going Wrong?

Your code is trying to grab the alt attribute directly from flkty.selectedElement, but that's actually pointing to the .carousel-cell container div—not the <img> inside it. Since divs don't have an alt property, you're getting undefined instead of the image's alt text.

The Fix

You just need to target the <img> element inside the selected carousel cell first, then pull its alt attribute. Here are two ways to do this, matching your code style:

Option 1: Using Native JavaScript

var $carousel = $('.carousel').flickity({ 
  imagesLoaded: true, 
  percentPosition: false 
}); 
var $caption = $('.caption'); 
var flkty = $carousel.data('flickity'); 

$carousel.on( 'select.flickity', function() { 
  // Find the img inside the selected carousel cell
  const selectedImg = flkty.selectedElement.querySelector('img');
  // Set caption text, with a fallback for cells without an img
  $caption.text(selectedImg ? selectedImg.alt : '');
}); 

Option 2: Using jQuery (Matches Your Existing Code)

var $carousel = $('.carousel').flickity({ 
  imagesLoaded: true, 
  percentPosition: false 
}); 
var $caption = $('.caption'); 
var flkty = $carousel.data('flickity'); 

$carousel.on( 'select.flickity', function() { 
  // Use jQuery to find the img in the selected cell and get its alt
  const altText = $(flkty.selectedElement).find('img').attr('alt') || '';
  $caption.text(altText);
}); 

Quick Note

I added a fallback (empty string) in both examples just in case you ever have a carousel cell without an image—this prevents your caption from showing undefined which looks messy.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:03:57