jQuery获取图像src


104

我希望当我单击按钮时,可以获得特定的img src并在div类img-block块中显示img src 。

的HTML

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

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

的CSS

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

JS

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

但是现在我面临的问题是获取img src。
因此,我使用Alert进行测试,结果是没有任何警报。

Answers:




4

完整网址使用

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

用于相对图像网址

$('#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' />


1

这就是你所需要的

 $('img').context.currentSrc

1

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

$('img#post_image_preview').src;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.