我想将img src内部链接更改为外部链接

时间:2019-01-16 14:04:27

标签: javascript php html image

<div class="view-content">
<img src="/img/img_01.png">
<img src="/img/img_02.png">
<img src="/img/img_03.png">
</div>

如果我想将其更改为

<div class="view-content">
<img src="http://example.com/img/img_01.png">
<img src="http://example.com/img/img_02.png">
<img src="http://example.com/img/img_03.png">
</div>

使用javascript或php str replace就像这样 我该怎么做。

var count = $('.view-content img').length; 
var url = window.location.hostname;
for(var i=0;i<count;i++){
  var imgurl = $('.view-content').eq(i).attr('src'); 
  $('.view-content img').eq(i).append(url+'/'+imgurl);
}

我已经尝试过这段代码,但是根本不起作用

5 个答案:

答案 0 :(得分:2)

您可以使用这种简单的脚本在每个图像的src参数的开头添加http。

const images = document.querySelectorAll('.view-content img')
images.forEach(item => {
  const src = item.getAttribute('src');
  const newSrc = 'http://example.com' + src;
  item.setAttribute('src', newSrc);
})
<div class="view-content">
<img src="/img/img_01.png">
<img src="/img/img_02.png">
<img src="/img/img_03.png">
</div>

答案 1 :(得分:0)

也许这个片段可以帮上忙,我所做的只是遍历img元素;抓住SRC并存储在临时变量中;附加了http://域+ src作为新的源属性。

<!DOCTYPE html>
<html lang="en">

  <head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title></title>

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">

  </head>

  <body>

    <!-- Page Content -->
    <div class="container">
      <div class="row">
        <div class="col-lg-12 text-center">
          <h1 class="mt-5">Test</h1>
            <img src="/img/img_01.png">
            <img src="/img/img_02.png">
            <img src="/img/img_03.png">
        </div>
      </div>
    </div>

    <!-- Bootstrap core JavaScript -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
    <script>
        $("img").each(function(){
          var src = $(this).attr('src');
          $(this).attr('src', 'http://www.blah.com' + src);
        })
    </script>
  </body>

</html>

答案 2 :(得分:0)

也许是主题的变体

let host='http://example.com/';
let col=document.getElementsByTagName('img');
col.forEach( img =>{
    if( !~img.src.indexOf( host ) )img.src = host + img.src;
});

答案 3 :(得分:0)

仅在带有ID的js中手动切换该怎么办?

document.getElementById("1stPic").src="https://cdn.pbrd.co/images/HS0VtcX.jpg";

答案 4 :(得分:0)

如果页面上所有 all 链接都需要一个新的基本URL,则可以完全避免使用JS并使用<base>元素。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base