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를 얻는 것입니다.
그래서 경고를 사용하여 테스트를 수행하면 결과가 아무것도 경고하지 않습니다.

답변:



6

likr을 찾을 수 있습니다.

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

4

전체 URL 사용

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


1

이것이 당신이 필요로하는 것입니다

 $('img').context.currentSrc

1

제 경우에는이 형식이 최신 버전의 jQuery에서 작동했습니다.

$('img#post_image_preview').src;
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.