问题
I need to output the current source of an image using a jQuery alert:
alert($('.someclass img').attr('currentSrc'));
...however the alert is outputting undefined.
For reference, the mark-up is as follows:
<div class="someclass">
<img srcset="http://example.com/A.png, http://example.com/A@2x.png 2x">
</div>
回答1:
currentSrc
is a property not an attribute. Use .prop('currentSrc')
$(function() {
console.log($("img").prop("currentSrc"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someclass">
<img srcset="https://webkit.org/demos/srcset/image-1x.png, https://webkit.org/demos/srcset/image-2x.png">
</div>
回答2:
try alert($('.someclass img').attr('srcset'));
来源:https://stackoverflow.com/questions/36684814/output-img-currentsrc-of-srcset-using-jquery