jQuery获取图片的src

137
我希望点击按钮后,能够获取特定的图片地址,并在 img-block 区块中显示该图片。 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

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

但是现在我面临的问题是获取img src。
因此我使用alert进行测试,结果是没有弹出任何内容。

8个回答

266

src应该用引号括起来:

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

14

完整网址请使用

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

使用相对图片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' />


8
您可以找到类似的内容。
$('.class').find('tag').attr('src');

3

html :

<img id="img_path_" width="24" height="24" src=".." class="img-fluid" alt=“">

js:

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

3

处理HTML DOM时(即this),必须使用数组选择器[0]从Javascript数组中检索jQuery元素。

$(this)[0].getAttribute('src');

2
在我的情况下,这种格式适用于最新版本的jQuery:
$('img#post_image_preview').src;

1
这是你需要的。
 $('img').context.currentSrc

0
jQuery(document).ready(function($){
                $('body').on('click','.button',function(){              
                    var imgsrc=$('.img1 img').attr('src');              
                    $(".img-block").append(imgsrc);
                })
            });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接