简体   繁体   中英

Image Preloading problem with jquery

here i am giving the code to preload image by jquery.

 var _images = ['/images/ajax-loader.gif'];
   $.each(_images, function (e) {
       $(new Image()).load(function () {
           //alert($(this).attr('src') + 'has loaded!');
       }).attr('src', this);
   });

the above code works fine because here we hard code the image path but when image path is stored in variable then it is not working.

here i am giving the code which gives error.

    var _images = '[' + data.d[0].LabelImagePath + ']';
                        $.each(_images, function (e) {
                            $(new Image()).load(function () {
                                $('#imgHolder').html("<img src='" + data.d[0].LabelImagePath + "' border=0/>");
                                $("#btnPrint").show();
                            }).attr('src', this);
                        });

this line return image path like /images/1Z520777777779.gif.

so please guide me how to preload images when image path is stored in variable with jquery by the above code. thanks

You are building up a string instead of an array (I dunno why). Your $.each() expects something that can be iterated.

Try creating an array instead, it will work:

var _images = [data.d[0].LabelImagePath];

Also, inside the $.each() , don't use data.d[0].LabelImagePath , because it will break your code when you're trying to preload more than one image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM