如何用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

