gpt4 book ai didi

jquery - 如何使用相同的 alt 包裹所有图像

转载 作者:行者123 更新时间:2023-12-01 03:58:42 26 4
gpt4 key购买 nike

这是我的代码

<div class="portfolio-project">
<img src="https://picsum.photos/id/31/800/800" alt="p1">
<img src="https://picsum.photos/id/32/800/800" alt="p2">
<img src="https://picsum.photos/id/33/800/800" alt="p3">
<img src="https://picsum.photos/id/34/800/800" alt="p1">
<img src="https://picsum.photos/id/35/800/800" alt="p2">
<img src="https://picsum.photos/id/36/800/800" alt="p3">
</div>

我想要这样的

<div class="portfolio-project">
<div class="p1">
<img src="https://picsum.photos/id/31/800/800" alt="p1">
<img src="https://picsum.photos/id/34/800/800" alt="p1">
</div>
<div class="p2">
<img src="https://picsum.photos/id/32/800/800" alt="p2">
<img src="https://picsum.photos/id/35/800/800" alt="p2">
</div>
<div class="p3">
<img src="https://picsum.photos/id/33/800/800" alt="p3">
<img src="https://picsum.photos/id/36/800/800" alt="p3">
</div>
</div>

我尝试将我的代码应用为:jQuery add alt tag to images with same src但我遇到了一个问题,我的代码有这样的多重换行。

$(function($) {
$("img").each(function(i, y) {
var src = $(y).attr('src');
var alt = $(y).attr('alt');
$("img[alt='" + alt + "']").wrapAll('<div class="' + alt + '"></div>');
});
});
img {
width:50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="portfolio-project">
<img src="https://picsum.photos/id/31/800/800" alt="p1">
<img src="https://picsum.photos/id/32/800/800" alt="p2">
<img src="https://picsum.photos/id/33/800/800" alt="p3">
<img src="https://picsum.photos/id/34/800/800" alt="p1">
<img src="https://picsum.photos/id/35/800/800" alt="p2">
<img src="https://picsum.photos/id/36/800/800" alt="p3">
</div>

如何解决?

最佳答案

您需要检查它是否已经包装,例如 $('.' + alt).length == 0

$(function($) {
$("img").each(function(i, y) {
var src = $(y).attr('src');
var alt = $(y).attr('alt');
if ($('.' + alt).length == 0)
$("img[alt='" + alt + "']").wrapAll('<div class="' + alt + '"></div>');
});
});
img {
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="portfolio-project">
<img src="https://picsum.photos/id/31/800/800" alt="p1">
<img src="https://picsum.photos/id/32/800/800" alt="p2">
<img src="https://picsum.photos/id/33/800/800" alt="p3">
<img src="https://picsum.photos/id/34/800/800" alt="p1">
<img src="https://picsum.photos/id/35/800/800" alt="p2">
<img src="https://picsum.photos/id/36/800/800" alt="p3">
</div>

关于jquery - 如何使用相同的 alt 包裹所有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com