从图像中获取 alt 属性并将其作为 class 添加到同一图像

Get the alt attribute from an image and add it as a class to the same image

我正在尝试从图库中的每张图片获取 alt 属性,然后将该文本作为 class 添加到同一图片。

到目前为止我已经试过了:

(document).ready(function(){

    var $grid = $('.gallery').imagesLoaded( function() {

    console.log ($(".gallery-item").length);
    // I get 14, the number of images in my gallery.

    $(".gallery-item").each(function() {
         var alt = $(this).attr( "alt" );
         console.log(alt);
         // I get 14 undefineds
         $(this).addClass(alt);
});

尝试:

var alt = $(this).find("img").attr("alt");

$(this).addClass(alt);

alt 属性不是强制性的,因此可能某些 img 没有它。如果您可以 post 您的 HTML 我相信我们会更有用。

无论如何,真正的问题是 alt 属性可以包含不允许的字符,或者如果用作 classes 可能会产生一些问题。例如 alt 可以包含空格,但这意味着 class 属性中有 2 个 classes(例如 "image of a ball" as alt results in 4 classes if you put this class 属性中的文本 )

所以如果你想这样做,我建议你至少用一些字符替换所有空格(“-”或“_”可能没问题)。