jQuery 获取图片 src

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19937162/
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-08-27 00:50:50  来源:igfitidea点击:

jQuery get the image src

jquery

提问by Chen-Tai

I hope when I click the button, I can get the specific img src and show the img src in the div class img-blockblock.

我希望当我点击按钮时,我可以得到具体的 img src 并在 div 类img-block块中显示 img src 。

HTML

HTML

<button class="button">Click</button>
<div class="img1">
    <img src="img.jpg" alt="">
</div>

<div class="img-block"></div>

CSS

CSS

.img-block{
    position: absolute;
    top:10%;
    right:10%;
    background-color: red;
    width: 500px;
    height: 500px;
}
.img1 img{
    width: 200px;
}

JS

JS

$('.button').click(function(){
  var images = $('.img1 img').attr(src);
  alert(images);      
});

But now I face the problem is to get the img src.
So I use alert to make the test, the result is it alert nothing.

但现在我面临的问题是获取 img src。
所以我使用alert来进行测试,结果是它没有任何警报。

回答by Stuart Kershaw

src should be in quotes:

src 应该用引号引起来:

$('.img1 img').attr('src');

回答by parth-BSP

You may find likr

你可能会发现likr

$('.class').find('tag').attr('src');

回答by NuOne

for full url use

用于完整的 url 使用

$('#imageContainerId').prop('src')

for relative image url use

对于相对图像 url 使用

$('#imageContainerId').attr('src')

function showImgUrl(){
  console.log('for full image url ' + $('#imageId').prop('src') );
  console.log('for relative image url ' + $('#imageId').attr('src'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>

<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />

回答by Nezir

In my case this format worked on latest version of jQuery:

就我而言,这种格式适用于最新版本的 jQuery:

$('img#post_image_preview').src;

回答by suzuko

This is what you need

这就是你需要的

 $('img').context.currentSrc