如何更改jQuery加载的img的src?

时间:2017-04-24 14:04:15

标签: javascript jquery html

我正在使用jQuery load()方法从另一个域的网页加载各种元素。脚本如下:

<script>
    $(function(){
        $("#a1").load("http://webpage.anotherdomain.com/ #another_a1");
        $("#img1").load("http://webpage.anotherdomain.com/ #another_img1");
        $("#span1").load("http://webpage.anotherdomain.com/ #another_span1");
    });
</script>

和HTML如下:

<div id="a1"></div>
<div id="img1"></div>
<div id="span1"></div>

所以结果HTML是

<div id="a1">
    <a id="another_a1" href="a_relative_url.aspx">description</a>
</div>
<div id="img1">
    <img id="another_img1" src="img_relative_url.ashx">
</div>
<div id="span1">
    <span id="another_span1">content</span>
</div>

问题是加载的a和img元素具有相对URL,因此超链接无法正常工作且图像不会显示。我该如何解决这个问题?

修改 有了你的答案,问题就解决了,脚本现在如下:

<script>
    $(function(){
        $("#a1").load("http://webpage.anotherdomain.com/ #another_a1"function(){
            $("#another_a1").attr("href",function(){
                return "http://webpage.anotherdomain.com/"+$("#another_a1").attr("href");
            });
        });
        $("#img1").load("http://webpage.anotherdomain.com/ #another_img1",function(){
            $("#another_img1").attr("src",function(){
                return "http://webpage.anotherdomain.com/"+$("#another_img1").attr("src");
            });
        });
        $("#span1").load("http://webpage.anotherdomain.com/ #another_span1");
    });
</script>

2 个答案:

答案 0 :(得分:0)

使用传递给load的回调函数,您可以在元素加载后修改元素的内容。

$("#span1").load("http://webpage.anotherdomain.com/ #another_span1",function(content) {
   //load was successful,
   //in this callback function, you can now access $('#span1').html() and modify it as you see fit.

   //do something to modify the content
   content = content.replace(...)

   //reset the content
   $('#span1').html(content);

});

答案 1 :(得分:0)

如果您对所加载的页面没有任何控制权,最好不要将其包含在您的网页上。

如果您仍想这样做,可以使用jQuery的attr()函数(http://api.jquery.com/attr/)。 $("#another_img1").attr("src", [yourUrl]);

相关问题