为 post 中的所有图像查找图像 src url

Find image src url for all the images in a post

简短摘要:我处于 Jekyll 的情况下,我需要为每个单独的图像找到 src url 并将其 post 返回到 href="imgurl"。 jQuery 或 Javascript.

到目前为止我尝试了什么:

$(document).ready(function(){

    var postTitle = document.title.replace(/ /g,'');   

    $("article img").each(function() {  
    imgsrc = this.src;
    console.log(imgsrc);
    });

    $("article img").wrap('<a href="' + imgsrc + '" data-lightbox="' + postTitle + '"></a>');

我将文章 img 包装在 a-tag 中的原因是因为我用于降价的 prose.io 会自动分配 p-tags 中的图像。

我最终想要做的是将所有图像分组在同一个 post (data-lightbox) 中,并从添加到页面的图像自动创建一个灯箱画廊。

使用我现有的代码,我已经设法从第一个添加的图像中获取 url,但不幸的是,post 中的所有图像都分配了相同的 url作为第一个。它们将 on-site 显示为正确的图像,但 url 与第一张图像(数组中的位置 [0])相同。当我单击图像时,灯箱打开并显示正确数量的图像,但它们都显示第一张图像。 console.log 正确打印 post 中图像的所有 url。

EDIT-BONUS:已验证!作为 bonus-question:如果我对替代文本做同样的事情,将其复制到 data-title 属性中,我将如何进行?目前有这个:

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

    $("article img").each(function() {
    $(this).wrap('<a href="' + this.src + '" data-lightbox="' + postTitle + '" data-title="' + altText + '"></a>');

});

同样,它只是为我获取第一张图片 alt,并将其分配给所有图片。

我希望你们中的一些人知道如何解决这个问题。

预先感谢您的宝贵时间!

每次有图像时,您都会覆盖 imgsrc

尝试这样的事情:

$("article img").each(function() {
    var src = this.src;
    var alt = $(this).attr("alt");
    $(this).wrap('<a href="' + src + '" data-lightbox="' + postTitle + '" data-title="' + alt + '"></a>');
});

查看.attr()了解更多信息!