【问题标题】:Correct Img Src Path with Javascript and Jquery使用 Javascript 和 Jquery 更正 Img Src 路径
【发布时间】:2015-11-18 06:48:02
【问题描述】:

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

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

但作为一个短期解决方案,我想应用一个 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 语句在正确的图像 URL 上的计算结果为 true,但问题在于 if 语句。替换似乎没有运行,并且图像的地址没有被修改。

我错过了什么?

【问题讨论】:

    标签: javascript jquery image src


    【解决方案1】:

    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/",""));
        }
    });
    

    【讨论】:

    • @isherwood 好的。我会这样做的。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      .attr('src') 只返回特定属性中的字符串。该字符串与它来自的 DOM 元素解除关联,因此对其执行的任何操作都不会返回到 DOM 元素中。你需要

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

      将更改后的字符串写回。

      【讨论】:

        【解决方案4】:

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

        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;
        });
        

        【讨论】:

          猜你喜欢
          • 2014-01-20
          • 2023-03-03
          • 2011-05-10
          • 2010-11-26
          • 2021-02-12
          • 1970-01-01
          • 2014-05-06
          • 1970-01-01
          • 2018-07-13
          相关资源
          最近更新 更多