【问题标题】:Remove resize at the end of img src删除 img src 末尾的 resize
【发布时间】:2014-11-09 05:19:53
【问题描述】:

我正在尝试删除页面上所有 img 元素的 img src 末尾的字符串。

现在出现的 img src 示例

http://www.example.com/B-UV-image-copy.jpg?resize=320%2C180

我希望它是怎样的

http://www.example.com/B-UV-image-copy.jpg

我正在尝试在页脚中使用 javascript 来查找所有 img 元素,然后从所有这些元素中删除 ?resize=320%2C180。字符串“?resize=320%2C180”在我想要影响的所有图像上始终相同。

目前我的代码如下所示:

<script>
  $('img').attr('src', function(index, attr) {
  return attr.replace("?resize=320%2C180", "");
  });
</script>

我很感激我可能会搞错这一切。目前,上面的脚本什么也没做,但我在 firebug 中遇到错误:

Uncaught TypeError: undefined is not a function 

如有任何帮助,将不胜感激。

【问题讨论】:

标签: javascript jquery html wordpress image


【解决方案1】:

您的代码有效。您只需要加载 DOM,并且需要确保 $ 绑定到 jQuery

<script>
   (function ($) {
      $(document).ready(function() {
          $('img').attr('src', function(index, attr) {
            return attr.replace("?resize=320%2C180", "");
          });
       });
   }(window.jQuery));
</script>

【讨论】:

  • jQuery(function($){ your code here }); 在一个紧凑的快捷版本中同时完成 DOM 准备和 IEFE(提供本地 $)。
  • 同意,但我想尽可能明确地解释说,实际上这两件事都需要发生才能让他的代码正常工作。
  • 在这种情况下不需要 IEFE。没有迹象表明与其他插件发生冲突(这在最近的项目中很少发生,主要是在遗留代码上)。
【解决方案2】:

为我工作。你只需要ensure that the DOM is ready 在你要求 jQuery 操作它之前:

$(function(){
    $('img').attr('src', function(index, attr) {
        return attr.replace("?resize=320%2C180", "");
    });
});

http://jsfiddle.net/os5rhw23/

【讨论】:

  • 您的意思是:“确保 DOM 已准备就绪”(jQuery 显然已加载,否则第一个 $ 将失败):)
  • @TrueBlueAussie 是的,我愿意。谢谢。
【解决方案3】:

使用 RegExp 从 URL 中剥离所有查询部分:

jQuery(function ($) {
    $('img').attr('src', function(index, attr) {
        return attr.replace(/\?.*$/i, '');
    });
});

【讨论】:

    【解决方案4】:

    其他两个答案是正确的,但是对于 DOM 就绪处理程序 jQuery 的本地范围 $ 最好的简写是 jQuery(function ($) { your code here}

    例如

    <script>
       jQuery(function ($) {
           $('img').attr('src', function(index, attr) {
              return attr.replace("?resize=320%2C180", "");
           });
       });
    </script>
    

    【讨论】:

      【解决方案5】:

      如果你想用纯 JS 做这个,在页脚中内联而不需要 jQuery,你可以简单地循环遍历所有图像 - 只要这个脚本在页面上的某个时间点之后图像(例如,就在关闭的身体之前)

      <body>
          <!-- some html, blah blah -->
          <script>
              var images = document.images,
                  i = images.length;
              while(i--) {
                  var image = images[i];
                  image.src = image.src.replace("?resize=320%2C180", "");
              }
          <script>
      </body>
      

      http://jsfiddle.net/os5rhw23/1/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-13
        • 2013-08-13
        • 1970-01-01
        • 1970-01-01
        • 2019-11-18
        • 1970-01-01
        • 1970-01-01
        • 2015-03-05
        相关资源
        最近更新 更多