2010-02-19 12 views
2

我正在製作lightbox,我遵循教程只是爲了讓這個更遠,而且我非常接近。我在與這條線的問題:jquery - 無法從圖像中拉動attr並應用到元素

}).attr('src', 'imghref'); 

,如果我用「圖像/ watercolor.jpg」,那麼它工作正常,但我想「imghref」是鏈接的用戶的href替換「imghref」點擊。

我的第二個問題是,如果我將'imghref'替換爲'images/watercolor.jpg'(用於測試目的),那麼當我刷新頁面時,它會自動加載圖像,而無需點擊鏈接,但我希望只有在用戶點擊鏈接時才加載圖片。 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('loading').append(img); 
     $(img).fadeIn('slow'); 
    }).error(function() { 

    }).attr('src', 'imghref'); 

}); 

回答

1

將變量傳遞給加載函數,並將其用作變量而不是字符串常量。另外,請確保您在全局範圍或與其使用的範圍相同的範圍內聲明loadImage。

$(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); 

    } 
}); 
5

要指定實際'imghref'爲文本,因爲你把它包在單引號,而不是變量的內容..

做這樣的

.attr('src', imghref)

1

看起來您正在使用'imghref'作爲loadImage()中的字符串常量。拿掉引號來代替使用變量的值。

$('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); 

});