2016-07-06 185 views
0

我想獲得div中每個圖像的alt標籤,並將它們列在<ul><li>中,但我不想重複使用alts。例如,如果2個imgs具有alt「example1」,我希望它僅在我的<ul><li>上列出一次。獲取所有的ALT標籤

我當前的代碼:

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> 

謝謝!

回答

1

需要創造獨特的ALT值的集合,並檢查任何附加

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

非常感謝你之前! :) –