jQuery รับภาพ src


105

ฉันหวังว่าเมื่อฉันคลิกปุ่มฉันจะได้รับ img src ที่เฉพาะเจาะจงและแสดง img src ในimg-blockบล็อกคลาส div

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
ดังนั้นฉันจึงใช้การแจ้งเตือนเพื่อทำการทดสอบผลที่ได้คือไม่มีการแจ้งเตือน

คำตอบ:




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' />



โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.