2011-03-09 65 views
2

在下面的代碼中,我希望在頁面加載時顯示第一個圖像,但是它不顯示任何內容,並且在Firebug中沒有錯誤。如何用JQuery獲取第一張圖片的圖片源?

我怎樣才能得到這條線的工作:

$('img#main').attr('src', $('img:first').src); 

全碼:

<!DOCTYPE html> 
<html> 
    <head> 
     <script type="text/javascript" src="http://www.google.com/jsapi"></script> 
     <script type="text/javascript"> 
      google.load('jquery', '1.5'); 
      google.setOnLoadCallback(function() { 

       $('img.thm').css({opacity: 0.7}); 
       $('img#main').attr('src', $('img:first').src); //doesn't work 

       $('img.thm').width(80).click(function() { 
        $('img#main').attr('src', this.src); 
       }); 
       $('img.thm').mouseover(function() { 
        $(this).css({opacity: 1.0}); 
       }); 
       $('img.thm').mouseout(function() { 
        $(this).css({opacity: 0.7}); 
       }); 
      }); 
     </script> 
     <style type="text/css"> 
      img.thm { 
       cursor: hand; 
       cursor: pointer; 
      } 
     </style> 
    </head> 
    <body> 
     <div id="menu"> 
      <img class="thm" src="images/test1.png"/> 
      <img class="thm" src="images/test2.png"/> 
      <img class="thm" src="images/test3.png"/> 
     </div> 
     <div id="content"> 
      <img id="main"/> 
     </div> 
    </body> 
</html> 

回答

9

使用正從$('img:first')圖像源是一個jQuery對象時.attr()

$('img#main').attr('src', $('img:first').attr('src')); 

The .src屬性用於表示圖像的DOM對象。你可以使用它像這樣(見.get()):

$('img#main').attr('src', $('img').get(0).src); 

但出於一致性的緣故,我會用.attr()

1
$('img#main').attr('src', $('img:first').attr('src')); 
相關問題