javascript 如何使用jquery获取img标签的src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33142106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the src of img tag using jquery
提问by Rohitashv Singhal
I have an HTML as follow :
我有一个 HTML 如下:
<ul class="thumbnails">
<li><a class="thumbnail" href="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_1-500x500.jpg" title="Canon EOS 5D"><img src="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_1-228x228.jpg" title="Canon EOS 5D" alt="Canon EOS 5D"></a></li>
<li class="image-additional"><a class="thumbnail" href="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_2-500x500.jpg" title="Canon EOS 5D"> <img src="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_2-74x74.jpg" title="Canon EOS 5D" alt="Canon EOS 5D"></a></li>
<li class="image-additional"><a class="thumbnail" href="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_3-500x500.jpg" title="Canon EOS 5D"> <img src="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_3-74x74.jpg" title="Canon EOS 5D" alt="Canon EOS 5D"></a></li>
</ul>
I want to get the src value
img. I have used the following code :
我想得到src value
img。我使用了以下代码:
var imgTag = $('.thumbnail').attr("href");
console.log(imgTag);
It gives the href
of the a tag
but I want the src of the img tag just after the a tag
what modification should I do ?
它给出了href
,a tag
但我想要 img 标签的 src 在a tag
我应该做什么修改之后?
回答by Milind Anantwar
image is child element of .thumbnail
. You need to use:
image 是 的子元素.thumbnail
。您需要使用:
$('.thumbnail').find('img').attr("src");
Change SRC of image:
更改图像的 SRC:
$('.thumbnail').find('img').attr("src", newSRC);
回答by Amit
To get the value of the src
attribute of your image, you need to request the src
attribute, not the href
attribute.
要获取src
图像的属性值,您需要请求src
属性,而不是href
属性。
To get the child of an element, use the child (direct descendant) selectorparent > child
.
要获取元素的子元素,请使用子(直接后代)选择器parent > child
。
In your case:
在你的情况下:
$('.thumbnail > img').attr('src');
回答by shani1123
You can get source using
您可以使用
$('.thumbnail img').attr('src');