如何使用JQuery获取第一张图片的图片来源? [英] How to get image source of first image with JQuery?
本文介绍了如何使用JQuery获取第一张图片的图片来源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,我希望在页面加载时显示第一张图像,但是它什么也不显示,并且在Firebug中没有错误.
In the following code, I want the first image to be displayed when the page loads, however, it doesn't show anything, and no error in Firebug.
我如何使这行工作:
$('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>
推荐答案
从作为jQuery对象的$('img:first')
获取图像源时,请使用.attr()
:
Use .attr()
when getting the image source from $('img:first')
which is a jQuery object:
$('img#main').attr('src', $('img:first').attr('src'));
.src
属性用于表示图像的DOM对象.您可以像这样使用它(请参见 .get()
):
The .src
property is for the DOM object representing the image. You could use it like this (see .get()
):
$('img#main').attr('src', $('img').get(0).src);
但是为了保持一致,我将使用.attr()
.
But for consistency's sake I would use .attr()
.
这篇关于如何使用JQuery获取第一张图片的图片来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文