I am trying to preload some images with a jQuery AJAX call, but am having real problems passing a (url) string into a function within the success function of the AJAX call (if that makes sense).
Here is my code as is stands:
//preloader for images on gallery pages
window.onload = function() {
setTimeout(function() {
var urls = ["./img/party/"]; //just one to get started
for ( var i = 0; i < urls.length; i++ ) {
$.ajax({
url: urls[i],
success: function(data,url) {
$(data).find("a:contains(.jpg)").each(function(url) {
new Image().src = url + $(this).attr("href");
});
}
});
};
}, 1000);
};
可以看到我(失败)try 将url传递到.each()
调用中,结果是url
接受递增整数的值.不知道为什么或者这些与什么有关,也许是jpg文件的数量?
...anyway, it should of course take the single value in my original urls array.
谢谢你的帮助——我似乎总是对这些回电感到有些纠结.
PROGESS?
So, I mucked around a bit, taking heed of comments from @ron tornambe and @PiSquared and am currently here:
//preloader for images on gallery pages
window.onload = function() {
var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];
setTimeout(function() {
for ( var i = 0; i < urls.length; i++ ) {
$.ajax({
url: urls[i],
success: function(data) {
image_link(data,i);
function image_link(data, i) {
$(data).find("a:contains(.jpg)").each(function(){
console.log(i);
new Image().src = urls[i] + $(this).attr("href");
});
}
}
});
};
}, 1000);
};
我试着把image_link(data, i)
放在这里、那里和任何地方(在每个嵌套函数中等等),但我得到了相同的结果:i
的值只记录为3.我怀疑这是因为对i
的所有引用都指向同一个对象,当异步任务实际达到image_link(data, i)
时,for...
循环就结束了(因此值为3).不用说,这将urls[i]
定义为"未定义".
Any (more) tips how I can get round this?