开发者

Set loaded image to an image control

开发者 https://www.devze.com 2023-03-19 22:10 出处:网络
I want to set an image control with some url but the image should only shown to the user when it is fully loaded. Below is my code:

I want to set an image control with some url but the image should only shown to the user when it is fully loaded. Below is my code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></titl开发者_运维百科e>

    <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>

Above I am loading the image of img1 in memory, now how I am going to set the same image to img2. I am loading image in memory of img1 because I want to show the img2 with img1 src at once.


First off, the HTML id element cannot start with a number, so id="1" is invalid (it may not work in every browser). I'd suggest using a common prefix (such as img). Thus 1 would become img1 and 2 would become img2.

Second, inside of an event handler, this is set to the element that triggered the event, so:

.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);
});

would work.

0

精彩评论

暂无评论...
验证码 换一张
取 消