Output img.currentSrc of srcset using jQuery

你。 提交于 2019-12-24 14:56:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!