Javascript 如何更改img src';多明是谁?

Javascript 如何更改img src';多明是谁?,javascript,jquery,Javascript,Jquery,如果有如下HTML代码 <img src="https://example.com/img_01.png"> <img src="https://example.com/img_02.png"> <img src="https://example.com/img_03.png"> <img src="https://example.com/img_04.png"> 我想改变这些,比如: <img src="https://example

如果有如下HTML代码

<img src="https://example.com/img_01.png">
<img src="https://example.com/img_02.png">
<img src="https://example.com/img_03.png">
<img src="https://example.com/img_04.png">

我想改变这些,比如:

<img src="https://example2.com/img_01.png">
<img src="https://example2.com/img_02.png">
<img src="https://example2.com/img_03.png">
<img src="https://example2.com/img_04.png">

我该怎么做呢?

你可以用

$('img').attr('src',”https://example2.com/img_01.png");
console.log(Array.from(document.querySelectorAll('img'))

您可以使用jQuery实现这一点:

<img src="https://example.com/img_01.png">
<img src="https://example.com/img_02.png">
<img src="https://example.com/img_03.png">
<img src="https://example.com/img_04.png">

您可以使用
replace
更改
url
内部循环以获得新的
url
,如下所示

$('img')。每个(函数(){
var newSrc=$(this.attr('src');
newSrc=newSrc.replace('example','example2')
$(this.attr('src',newSrc);
});

你可以这样试试

var newDOmain=”https://example2.com/";
$('img')。每个(函数(){
var imgName=$(this.attr('src').split('/').pop();
$(this.attr('src',newDOmain+imgName);
$(this.attr('alt',newDOmain+imgName);
})

如果有一天您的url更改为“”,那么如果您将使用直接字符串替换,则必须修改代码。因此,为了使您的代码更有效,请使用regex方法进行同样的操作

var domainRegex = /\/{2,}((?:[^\.]+\.)*\w+)\//;
$("img").each(img => {
    img.src = img.src.replace(img.src.match(domainRegex)[1], "example2.com");
});

此正则表达式可以将任何域名替换为您选择的域名。

我无法手动编辑,我的意思是我需要将example.com更改为example2.comautomatically@Te你这是什么意思。查看更改的代码片段的结果
var domainRegex = /\/{2,}((?:[^\.]+\.)*\w+)\//;
$("img").each(img => {
    img.src = img.src.replace(img.src.match(domainRegex)[1], "example2.com");
});