获取所有 ALT 标签

Get all ALT tags

我想在 div 中获取每个图像的 alt 标签,并将它们列在 <ul><li> 中,但我不想要重复的 alt。例如,如果 2 个 imgs 有 alt "example1",我希望它只在我的 <ul><li>.

上列出一次

我当前的代码:

JS

$('.img-produto > img').each(function(){
  $('.filters').append('<li>'+ $(this).attr('alt') +'</li>');
});

HTML

<ul class="filters"></ul>
<div class="img-produto">
<img src="img link" alt="example1" />
<img src="img link" alt="example1" />
</div>

谢谢!

需要创建唯一 alt 值的集合并在附加任何内容之前进行检查

var alts = {};
$('.img-produto > img').each(function(){
  var alt = $(this).attr('alt');
  if(!alts[alt]){
      alts[alt] = true;
      $('.filters').append('<li>'+ alt  +'</li>');
  }     
});