2015-07-05 115 views
0

我基本上是“创造”的基础上的信息完全来自#1以下功能不与警报(属性字符串)注册一个属性:jQuery的功能设置

function PreloadImageSources(arrayOfImageSources) 
{ 
    // call with PreloadImages(['src1', 'src2', etc]) 

    var newImage = $('<img />'); 

    $(arrayOfImageSources).each(function() { 
    /* 
     alert(this); // OK 
    */ 
     newImage.get(0).src = this; // explicit iteration because of .each 
    }); 

/* 
    alert(newImage.get(0).src); // still OK! 
*/ 

    // return the new array of img objects, each with their .src set 
    return $('<img />'); 
} 

两个警报显示函数内正确的字符串。但是,一旦我从函数返回,

var shutterImg = PreloadImageSources([options.shutterImgSrc]) [0]; 
alert(shutterImg.src); 

该警报显示什么,如果它不存在,尽管我刚分配它的函数里面的事实。

我缺少什么基本内核?

+1

有显示如何预加载图像中的多个其他答案:[图像预加载JavaScript的支持事件(http://stackoverflow.com/questions/8264528/image-preloader-javascript-that-supports-events/8265310#8265310),[是否有可能在渲染前在缓存中插入图像](http://stackoverflow.com/questions/8831345/is-it-possible-to-insert-images-in-cache-before-rendering/8831405#8831405)和[有没有办法将图像加载到用户的缓存异步?](http://stackoverflow.com/questions/8450068/is-there-a-way-to-load-images-to-users -cache-asynchronously/8450190#8450190) – jfriend00

+0

'return $('');'返回一个带有一个新的图像对象的jQuery对象,它没有'.src'属性,这就是为什么你的alert没有显示一个src网址。我不知道你为什么回来,因为它没有任何用处,并且与你预先加载的图片没有任何关系。 – jfriend00

+0

谢谢大家......谢谢你,我发现我的错误... .attr('src',this)是正确的,但.attr('src')=这不是 –

回答

0

您正在提醒(并返回)新图像的src,而不是您在循环中创建的图像。

为图像列表添加到您的网页时可能会做这样的事情:

function PreloadImageSources(arrayOfImageSources) { 
    var arrayOfImages = []; 
    $(arrayOfImageSources).each(function() { 

     // create a new image with jQuery and set the src of the image 
     var $img = $('<img />').attr('src', this); 

     // add the new image to an array 
     arrayOfImages.push($img); 

    }); 

    return arrayOfImages; 
} 

var imageArray = PreloadImageSources(sourcesArray); 

// alert the src of the first image 
alert(imageArray[0].attr('src')); 

// or iterate over your array of images 
$(imageArray).each(function() { 

    // add each to the dom 
    $('body').append(this); 

}); 
+0

谢谢大家......感谢你,我发现我的错误... .attr('src',this)是正确的,但是.attr('src')=这不是 –

+0

也是你返回$(“”)你正在创建一个新的图像,不会返回您添加源的人。 @ user3104710的答案是这里最优雅的解决方案。 – som

0

由于您使用的源阵列使用每次总是返回最后一个元素。但是,这也是一个单一的对象而不是一组对象。因为你的代码不工作。

请检查以下测试代码。

function PreloadImageSources(arrayOfImageSources) 
{ 
    return jQuery.map(arrayOfImageSources, function(imageSrc){ 
      return jQuery("<img />").attr("src", imageSrc); 
    }); 
} 
+0

感谢som&user3104710 ......感谢你,我发现了我的错误... .attr('src',this)是正确的,但.attr('src')=这不是 –