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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:09:42  来源:igfitidea点击:

How to get the src of img tag using jquery

javascriptjqueryhtml

提问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 valueimg. I have used the following code :

我想得到src valueimg。我使用了以下代码:

var imgTag =  $('.thumbnail').attr("href");
        console.log(imgTag);

It gives the hrefof the a tagbut I want the src of the img tag just after the a tagwhat modification should I do ?

它给出了hrefa 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 srcattribute of your image, you need to request the srcattribute, not the hrefattribute.

要获取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');