jQuery向具有相同src的图像添加alt标签 [英] jQuery add alt tag to images with same src
本文介绍了jQuery向具有相同src的图像添加alt标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有许多图像具有相同的URL来源,但只有第一幅图像带有Alt标记,因此如何将alt添加到具有相同URL的另一幅图像中?
There are many images with same URL source but the first image only that has the Alt tag, so how can I add alt to the other image with the same source?
$(function(){
var srcs = [],
alt = '',
title = '',
temp;
$("img").filter(function(){
temp = $(this).attr("src");
alt = $(this).attr("alt");
title += $(this).attr("title");
if($.inArray(temp, srcs) < 0){
srcs.push(temp);
srcs.push(alt);
srcs.push(title);
return false;
}
return true;
}).attr('alt',alt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="colourDots">
<img alt="aaa" title="axxx" src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
<img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
<img alt="bbb" title="axxx" src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
<img src="/out/pictures/generated/product/8/300_450_100/60028.sw.jpg"/><br>
<img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
<img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
<img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
</div>
我只需要过滤图像即可
所有具有相同源URL的图像.
All images that have same source URL.
将alt标签复制到其他没有alt但具有相同源URL的图片
Copy the alt tag to other images that haven't alt but have same source URL
推荐答案
- 获取所有唯一的src属性,
- 对于每个唯一的src属性,获取使用该属性的所有图像
- 对于每个集合,找到具有
alt
的成员,然后将其关联到整个集合.
- get all unique src attributes,
- for each unique src attribute, get all images that use it
- for each set, find a member with
alt
and then assing that to the entire set.
在代码中:
const uniques = [];
const imgs = $('img');
imgs.each(function () {
let src = this.src;
if (uniques.indexOf(src) === -1) uniques.push(src);
});
uniques.forEach(src => {
let srcd = imgs.filter("img[src='"+src+"']");
let alt = srcd.filter('[alt]').first().attr('alt');
srcd.each( function() {
$(this).attr('alt',alt);
})
});
这篇关于jQuery向具有相同src的图像添加alt标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文