[英]Find image src url for all the images in a post
简短摘要:在Jekyll的情况下,我需要为每个图像查找src url,并将其发回到a 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中的原因是因为我用于markdown的prose.io自动在p-tag中分配了图像。
我最终要做的是将所有图像分组在同一帖子(数据灯箱)中,并从添加的图像到页面自动创建灯箱图库。
使用现有的代码,我设法从添加的第一个图像中获取url,但是不幸的是,帖子中的所有图像都分配了与第一个相同的url。 它们在现场显示为适当的图像,但是url与第一个图像相同(数组中的位置[0])。 当我单击图像时,灯箱将打开,并显示正确数量的图像,但它们都显示第一张图像。 console.log正确打印帖子中图像的所有URL。
编辑奖金:已验证! 一个额外的问题:如果我要对alt文本执行相同的操作,然后将其复制到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()
以获得更多信息!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.