2011-07-11 56 views
0

我想設置一個帶有某個url的圖像控件,但該圖像只能在滿載時顯示給用戶。下面是我的代碼:將加載的圖像設置爲圖像控件

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title></title> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 

</head> 
<body> 
    <img id="1" /> 
    <img id="2" /> 
</body> 

<script type="text/javascript"> 

    $("<img/>").attr("src", $("#1").attr("src")) 
       .load(function() { 
        //How to set image 2 with with image which I just loaded 
       }); 
</script> 

</html> 

上面,我是裝IMG1的形象記憶,我現在該怎麼要去相同的圖像設置爲IMG2。我在img1的內存中加載圖像,因爲我想一次顯示img2和img1 src。

回答

1

首先,HTML id元素不能以數字開頭,因此id="1"無效(它可能不適用於每個瀏覽器)。我建議使用一個通用的前綴(如img)。因此1將變爲img12將變爲img2

其次,事件處理程序的內部,this設置爲觸發事件的元素,所以:

.load(function() { 
    // If you want to use the same element to pre-load multiple images 
    this.src = document.getElementById("img2").src; 

    // Or, if you want to set the pre-loaded image somewhere in the DOM 
    document.getElementById("img2").src = this.src; 

    // Or, if you want to inject this now pre-loaded img tag into the DOM directly 
    $("some_selector").append(this); 
}); 

會工作。

+0

你的意思是說「document.getElementById(」img2「)。src = this.src」 –

+0

@搖滾 - 是的,我誤解了你,並認爲你想使用相同的圖像加載第一個圖像後第一個完成加載。我會更新我的答案。 –