0

我正在寻找的是如何使用 java 脚本更改页面上的所有 img src。

如果说:

<img src="myimg1-small.png"></img>
<img src="myimg2-small.gif"></img>
<img src="myimg3-small.jpg"></img>
....... 

我只想将“-small”更改为“-large”并保留第一部分和扩展名。

如果有人可以帮助我,那将非常感谢。

4

5 回答 5

3

这是 JQuery 代码。

$('img').each(function(){
    $(this).attr('src',$(this).attr('src').replace(/-small\./g,'-large'));
});
于 2013-03-08T18:02:47.787 回答
1
$('img').each(function(){
    $(this).attr('src', $(this).attr('src').replace('-small','-large'));
});

Edit: I notice several of us answered essentially the same within a minute or so of each other. But, a couple of notes:

(1) Don't use a regular expression when a simple string match will do the job more efficiently.

(2) I included the hyphen (-) in my match so as not to accidentally confuse it with an image name that has the string 'small' without the hyphen. After all, if the image is of a small flower, for example, and the image name is 'smallflower-small.jpg', the match that doesn't use the hyphen breaks.

于 2013-03-08T18:05:12.747 回答
1
$('img[src^="myimg1-small"]').attr('src', function() {
    return this.src.replace('small', 'large');
});
于 2013-03-08T18:04:15.540 回答
1

如果你想要常规的 js:

var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
    imgs[i].src = imgs[i].src.replace('small','large');
}
于 2013-03-08T18:03:46.873 回答
0

使用 jQuery,您可以:

$(document).ready(function (){
    $('img').each(function (){
        $(this).attr('src', $(this).attr('src').replace('small', 'medium'))
    })
});

这是小提琴

于 2013-03-08T18:04:26.533 回答