开发者

jQuery preload images from list

开发者 https://www.devze.com 2023-04-10 10:35 出处:网络
I want to preload rollover images in jQuery but the list of images is inside 开发者_开发技巧list of like this:

I want to preload rollover images in jQuery but the list of images is inside 开发者_开发技巧list of like this:

<li><a href="/images/1.jpg"></a></li>
<li><a href="/images/2.jpg"></a></li>
<li><a href="/images/3.jpg"></a></li>

==========

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

var imagelist = $('li a').attr("href");
preload(imagelist);

I changed the last line so it just grab the href from my list. Original script was from: Preloading images with jQuery

Is this correct?


You can do this:

var imagelist = $('li a').each(function() {
    preload($(this).attr("href"));
});

Or you can do this:

$.fn.preload = function() {
    this.each(function(){
        //alert("preloading " + $(this).attr("href"));
        $('<img/>')[0].src = $(this).attr("href");
    });
}
$('li a').preload();

jsFiddle


You can use $.map to convert the nodeList into an array of hrefs:

var imageList = $('li a').map(function() {
    return this.href;
});

preload(imageList);

Or skip the preload function and do a simple loop instead:

$('li a').each(function() {
    (new Image).src = this.href;
});

If you want to use it as a plugin try:

$.fn.preload = function() {
    return this.each(function() {
        (new Image).src = this.href;
    });
};

$('li a').preload();


You can populate your imagelist like this to make it an array:

var imagelist = [];
$('li a').each(function(){
  imagelist.push($(this).attr('href'));
})
0

精彩评论

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