jquery替换url图像中的字符串

时间:2017-02-25 18:46:02

标签: javascript jquery html

请帮帮我     如何从s120替换字符串url图像

S120 /demo%2Bproduct%2Blipstik.jpg

S400 /demo%2Bproduct%2Blipstik.jpg

//jQuery
$(document).ready(function(){
  $("#largeimage").click(function(){
        $(".container img").attr("src").replace("s120","s400");
    });
});

HTML

<div class="container center">
  <img src="https://2.bp.blogspot.com/-NwKHFcL48ZA/WJ2FANm2TXI/AAAAAAAAA6Y/hE-85KroGacBYy26mnEbkEGYFcnyWWv4gCLcB/s120/demo%2Bproduct%2Blipstik.jpg">
</div>
<p>
<button class="center" id="largeimage">Large Image to 400</button>
</p>

DEMO

2 个答案:

答案 0 :(得分:2)

您没有更新属性,使用带有attr()方法的回调来执行此操作,该方法将旧值保存为第二个参数。

$(document).ready(function() {
  $("#largeimage").click(function() {
    $(".container img").attr("src", function(i, src) {
      return src.replace("s120", "s400");
    });
  });
});

答案 1 :(得分:0)

另一种方法 - 在img函数中更改attr src。

$(document).ready(function(){
  $("#largeimage").click(function(){
     var src = $(".container img").attr("src");
     $(".container img").attr("src", src.replace("s120","s400"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container center">
  <img src="https://2.bp.blogspot.com/-NwKHFcL48ZA/WJ2FANm2TXI/AAAAAAAAA6Y/hE-85KroGacBYy26mnEbkEGYFcnyWWv4gCLcB/s120/demo%2Bproduct%2Blipstik.jpg">
</div>
<p>
<button class="center" id="largeimage">Large Image to 400</button>
</p>