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

时间:2018-11-30 15:18:01

标签: javascript jquery html image

<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替换它。

2 个答案:

答案 0 :(得分:3)

这里是用正则表达式替换它的方式,该正则表达式为随机显示的部分寻找任何数字和小写字母。

post_install do |installer|
    print "Setting the default SWIFT_VERSION to 4.2\n"
    installer.pods_project.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '4.2'
    end

    installer.pods_project.targets.each do |target|
        if ['SomeTarget-iOS', 'SomeTarget-watchOS'].include? "#{target}"
            print "Setting #{target}'s SWIFT_VERSION to 3.0\n"
            target.build_configurations.each do |config|
                config.build_settings['SWIFT_VERSION'] = '3.0'
            end
        else
            print "Setting #{target}'s SWIFT_VERSION to Undefined (Xcode will automatically resolve)\n"
            target.build_configurations.each do |config|
                config.build_settings.delete('SWIFT_VERSION')
            end
        end
    end
end
var img = document.querySelector(".fotorama__img");
var src = img.src;
img.src = src.replace(/cache\/[0-9a-z]+\//, '');
console.log(img.src);

答案 1 :(得分:1)

使用.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">