2011-03-09 70 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'));