簡體   English   中英

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

[英]How to change src of img loaded by jQuery?

我正在使用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>

您可以使用傳遞給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);

});

如果您對正在加載的頁面沒有任何控制權,最好不要將其包含在網頁中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM