2

我确定这很简单,但我无法弄清楚。

我有这个 HTML:

<img src="/7290/9200572193_f95fb66c50_m.jpg" />

我需要更改为

<img src="/7290/9200572193_f95fb66c50_b.jpg" />

这并不总是相同的图像,但_m.jpgand_b.jpg是。我怎么能用 jQuery 做到这一点?

4

4 回答 4

2

You can do:

var imgSrc = "/7290/9200572193_f95fb66c50_m.jpg";
imgSrc = imgSrc.replace("_m.jpg", "_b.jpg");
于 2013-07-03T19:36:03.313 回答
1

Something like this may help you:

$( "img" ).each(function() {
  var src = $( this ).attr( "src" );
  $( this ).attr( "src", src.replace( /_m\.(.*)$/, "_b.$1" ) );
});

This will not depend on the extension of your src attribute.

于 2013-07-03T19:36:46.003 回答
1

使用 .循环遍历“img”标签$("img").each(function(){ doStuff(); });。用 更改属性attr("attribute","new_value"),用 获取属性attr("attribute")。替换为replace("from","to")

$("img").each(function(){
  $(this).attr("src",$(this).attr("src").replace("_m","_b"));
});
于 2013-07-03T19:37:26.420 回答
0

In short, use.replace. Such as:

"/7290/9200572193_f95fb66c50_m.jpg".replace('_m.jpg', '_b.jpg');
/*  OR  */
var url = "/7290/9200572193_f95fb66c50_m.jpg";
url.replace('_m.jpg', '_b.jpg');

You use .each() in jQuery to loop through a group of elements. Thus you can use a simple selector like $('img') to select all images on the view and then make changes in the callback method. You would then use .prop to both set and get the current src and change it using old fashioned .replace

$("img").each(function(i) {
    $(this).prop("src", $(this).prop("src").replace('_m.jpg', '_b.jpg'));
});

Example

于 2013-07-03T19:36:18.680 回答