使用 Javascript 和 Jquery 更正 Img Src 路径

Correct Img Src Path with Javascript and Jquery

我在一个网站上工作,该网站的内容很重要,来自具有不同域的旧网站。大约一半的图像具有工作良好的相对路径。另一半具有与旧域硬编码的绝对路径。旧站点已被删除,因此这些图像不再有效。然而,这些图像确实被导入,并存在于新服务器上。将这些路径更改为相对路径 URL 可解决问题。

长期解决方案是通过每个页面从这些图像 src URLs 中删除旧域。

但作为短期解决方案,我想应用 javascript 或 jquery 解决方法,循环遍历页面上的每个 img,检查每个的 url图像,如果它包含旧域,请将其删除。到目前为止,我还没有取得太大的成功。

这是我的示例 HTML:

<p><img src="somepicture.jpg"></p> <!-- this works -->
<p><img src="https://www.oldwebsitedomain.com/someotherpicture.jpg"></p> <!-- this doesn't -->

这是我写的javascript/jquery:

$("img").each(function() {
    if ($(this).attr("src").indexOf("oldwebsitedomain.com") > -1) {
        $(this).attr("src").replace("https://www.oldwebsitedomain.com/","");
        }
});

如果我 console.log "this",我将正确获取页面上的所有 img 对象。如果我控制台记录“$(this).attr("src")”,我会得到每个图像的 URL。我可以验证我的 if 语句在正确的图像 URLs 上的计算结果为真,但问题出在 if 语句中。替换似乎没有 运行,图像的地址也没有被修改。

我错过了什么?

.attr('src') 仅 returns 特定属性中的字符串。该字符串与其来源的 DOM 元素分离,因此对其执行的任何操作都不会返回到 DOM 元素。你需要

str = $(this).attr('src');
$(this).attr('src', str.replace(....));

将更改后的字符串写回。

您需要重新设置图片来源属性。

var newsrc = $(this).attr("src").replace("https://www.oldwebsitedomain.com/","");
$(this).attr("src", newsrc);

.attr( attributeName, function )也可以用来重置图片来源。使用示例,您不需要使用 .each()

$("img").attr('src', function(_, value) {
    return value.indexOf("oldwebsitedomain.com") > -1 ?
        value.replace("https://www.oldwebsitedomain.com/","") :
        value;
});

How to set and get an attribute.

要设置任何属性的值 jquery 使用以下语法, $(this).attr("src", 'new value');。要获取值 attribute = $(this).attr("src"),请使用它。我将这两个组合成一行。

$("img").each(function() {
    if ($(this).attr("src").indexOf("oldwebsitedomain.com") > -1) {
        $(this).attr("src", $(this).attr("src").replace("https://www.oldwebsitedomain.com/",""));
    }
});

为了使用 jquery 更改属性,您必须将第二个参数传递给函数调用:

$(this).attr("src", "new src value");