如何获取带javascript的图片alt标签?

How to get the image alt tag with javascript?

我无法使用 javascript 获取图像 alt 标签。这可能吗?如何实现?

也许是这样的:$caption.text(flkty.selectedElement).attr('alt') (最后 javascript 行)

但我没有让它工作...

谢谢!

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

var $caption = $('.caption');
// Flickity instance
var flkty = $carousel.data('flickity');

$carousel.on( 'select.flickity', function() {
  // set image caption using img's alt
  $caption.text( flkty.selectedElement.alt )
});
.carousel-cell {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.carousel-cell img {
  /* display: block; */
  /* max-height: 100%; */
  max-width: 100%;
}

p {
  text-align: center;
}
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">

<div class="carousel">
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/orange-tree.jpg"  alt="orange tree" />
  </div>
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/submerged.jpg" alt="submerged" />
   </div>
</div>
<p class="caption">&nbsp;</p>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>

使用attr

const img = document.getElementById('image')

const alt = img.getAttribute('alt')

console.log(alt)
<img id="image" src="https://picsum.photos/200/300" alt="this it the alt attribute" />

jQuery:

const alt = jQuery("#image").attr('alt')

console.log(alt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="image" src="https://picsum.photos/200/300" alt="this it the alt attribute" />

您的代码中有一个小错误:

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

var $caption = $('.caption');
// Flickity instance
var flkty = $carousel.data('flickity');

$carousel.on('select.flickity', function() {
  // set image caption using img's alt
  $caption.text($(flkty.selectedElement).find('img').attr('alt'))
});
.carousel-cell {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.carousel-cell img {
  max-width: 100%;
}

p {
  text-align: center;
}
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">

<div class="carousel">
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/orange-tree.jpg" alt="orange tree" />
  </div>
  <div class="carousel-cell">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/submerged.jpg" alt="submerged" />
  </div>
</div>
<p class="caption">&nbsp;</p>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>