使用jQuery替换HTML内容中的动态关键字


<div class="fotorama__stage__frame magnify-wheel-loaded fotorama_vertical_ratio fotorama__loaded fotorama__loaded--img fotorama__active" aria-hidden="false" data-active="true" style="left: 0px;" href="https://static.domain.com/media/catalog/product/cache/713229083fb198/h/a/123.png">
<img src="https://static.domain.com/media/catalog/product/cache/713229083fb198/h/a/123.png" class="fotorama__img" aria-hidden="false"></div>

我想从IMG属性中替换/cache/713229083fb198/并再次加载该图像。

来自

https://static.domain.com/media/catalog/product/cache/713229083fb198/h/a/123.png

https://static.domain.com/media/catalog/product/h/a/123.png

我想用jQuery替换它。

以下是如何用正则表达式替换它,正则表达式用于查找任意数字,小写字符用于查找随机部分。

var img = document.querySelector(".fotorama__img");
var src = img.src;
img.src = src.replace(/cache/[0-9a-z]+//, '');
console.log(img.src);
<div class="fotorama__stage__frame magnify-wheel-loaded fotorama_vertical_ratio fotorama__loaded fotorama__loaded--img fotorama__active" aria-hidden="false" data-active="true" style="left: 0px;" href="https://static.domain.com/media/catalog/product/cache/713229083fb198/h/a/123.png">
<img src="https://static.domain.com/media/catalog/product/cache/713229083fb198/h/a/123.png" class="fotorama__img" aria-hidden="false"></div>

使用.attr( function )更改图像的src属性。在函数中,使用.replace()中的正则表达式来匹配字符串的目标部分。

$(".fotorama__img").attr("src", function(i, src){  
return src.replace(//cache/[^/]+/, "");
});
console.log($(".fotorama__img").attr("src"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://static.domain.com/media/catalog/product/cache/713229083fb198/h/a/123.png" class="fotorama__img" aria-hidden="false">

最新更新