gpt4 book ai didi

javascript - 使用 jQuery 从图像源的文件名复制值以处理并粘贴到 html 中?

转载 作者:行者123 更新时间:2023-11-30 18:58:42 25 4
gpt4 key购买 nike

您好,我正在尝试使用 jQuery/javascript 让我的生活更轻松。我正在尝试使用它自动填充各种 html 元素,其中包含来自图像文件名的地点和国家名称。以下是我必须使用的一些 html 示例:

<div class="boxgrid">
<a href="gallery/angkor - cambodia.jpg" title="[PLACE] - [COUNTRY]">
<img src="gallery/thumbs/angkor - cambodia.jpg" alt="[PLACE] - [COUNTRY]" width="100" height="100"/>
</a>
<div class="boxcaption">
<span class="place">[PLACE]</span>
<span class="country">[COUNTRY]</span>
</div>
</div>

想象一下这个 html block 对于图库中的每个图像都重复了多次,所以我假设需要使用 .each()。

想法是 [NAME OF PLACE] 和 [NAME OF COUNTRY] 应该使用图像的文件名填充,使用 -(破折号)作为两个值之间的分隔符。我怎样才能用 jQuery/javascript 完成这个? (我意识到我应该使用服务器端语言或以另一种方式解决这个问题,但这是我的限制)

作为奖励,每个值的首字母都应大写,例如 Angkor - Cambodia。

谢谢,如有任何帮助,我们将不胜感激。

最佳答案

这是完整的代码,其中包含 Place 和 Country 的第一个字母的 trim 和大写。

String.prototype.capitalize = function(){
return this.replace(/\S+/g, function(a){
return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
});
};

$(function(){
$('.boxgrid').each(function(){
var placeCountry = $(this).find('img').attr('src')
.replace('gallery/thumbs/','')
.replace('.jpg','').capitalize();

var place = $.trim(placeCountry.split('-')[0]);
var country = $.trim(placeCountry.split('-')[1]);
$(this).find('a').attr('title',placeCountry);
$(this).find('img').attr('alt',placeCountry);
$(this).find('.place').html(place);
$(this).find('.country').html(country);
});
});

关于javascript - 使用 jQuery 从图像源的文件名复制值以处理并粘贴到 html 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/894426/

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