有没有更有效的方法来做到这一点,我的意思是除了使用全局?我讨厌使用全局变量,但我似乎无法弄清楚如何将href属性传递给函数。
$(document).ready(function(){
var src
$('.thumbs li a').click(function(){
src=$(this).attr('href')
loadImage();
return false;
})
function loadImage(){
var img = new Image();
$(img).load(function () {
//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
$(this).hide();
$('.large_img_holder').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
}).attr('src', src );
}
});
答案 0 :(得分:4)
我不确定这是否是您所追求的,但如果您允许loadImage
函数将src
作为参数,则可以避免定义src
变量在ready
函数中:
$(document).ready(function(){
$('.thumbs li a').click(function(){
var src=$(this).attr('href')
loadImage(src);
return false;
})
function loadImage(src){
var img = new Image();
$(img).load(function () {
//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
$(this).hide();
$('.large_img_holder').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
}).attr('src', src );
}
});
答案 1 :(得分:1)
您可以简单地将其作为参数传递:
function loadImage(new_src){
var img = new Image();
$(img).load(function () {
//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
$(this).hide();
$('.large_img_holder').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
}).attr('src', new_src );
});
}
$('.thumbs li a').click(function(){
loadImage($(this).attr('href'));
return false;
})
答案 2 :(得分:1)
首先,src
变量在$(document).ready(function(){/*...*/};
内声明,因此它不是全局变量。此外,您可以使用loadImage
函数的参数而不是src
变量:
$(document).ready(function(){
var loadImage = function(src){
var img = new Image();
$(img).load(function () {
//$(this).css('display', 'none');
//.hide() doesn't work in Safari when the element isn't on the DOM already
$(this).hide();
$('.large_img_holder').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
}).attr('src', src );
};
$('.thumbs li a').click(function(){
loadImage($(this).attr('href'));
return false;
});
});