Jquery - having trouble pulling attr from image and applying to an element
i'm making a lightbox, i've followed tutorials just to get this far, and i'm so close. i'm having problems with this line:
}).attr('src', 'imghref');
if i replace 'imghref' with 'images/watercolor.jpg' then it works fine, but i want 'imghref' to be the href of the link the user clicks on.
my second problem, is that if i replace 'imghref' with 'images/watercolor.jpg'(for testing purposes), then when i refresh the page, it loads the image automatically without me ever having clicked on the link, but i want the image to load only when the user clicks on the link. ARRGGG!!!!
$(function (){
$('a').click(function() {
var imghref = $(this).attr("href");
loadImage();
return false;
});
});
$(function loadImage() {
var img = new Image();
$(img).load(function () {
$(img).hide();
$('#loader').removeClass('l开发者_如何学运维oading').append(img);
$(img).fadeIn('slow');
}).error(function () {
}).attr('src', 'imghref');
});
You are assigning the actual 'imghref'
as text, since you wrap it in single quotes, and not the contents of the variable..
do it like this
.attr('src', imghref)
Pass the variable to the load function and use it as a variable instead of a string constant. Also, make sure that either you declare loadImage in the global scope or the same scope in which its used.
$(function (){
$('a').click(function() {
var imghref = $(this).attr("href");
loadImage(imghref);
return false;
});
function loadImage(href) {
var img = new Image();
$(img).load(function () {
$(img).hide();
$('#loader').removeClass('loading').append(img);
$(img).fadeIn('slow');
}).error(function () {
}).attr('src', href);
}
});
It appears you are using 'imghref' as a string constant in loadImage(). Take away the quotes to use the value of the variable instead.
$('a').click(function() {
var imghref = $(this).attr("href");
loadImage();
return false;
});
$(function loadImage() {
var img = new Image();
$(img).load(function () {
$(img).hide();
$('#loader').removeClass('loading').append(img);
$(img).fadeIn('slow');
}).error(function () {
}).attr('src', imghref);
});
精彩评论