jsfiddle
$('img').click(function () {
alert($(this).prop('src'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/tags/smiley.gif" />
<img src="" style="width: 10px; height: 10px; border: 1px solid;">
When I click the second image, it alerts http://stacksnippets.net/js.
Why?
According to the official doc :
HTMLImageElement.src Is a DOMString that reflects the src HTML attribute, containing the full URL of the image including base URI.
which obviously means that, without any path given into src, the src attribute will only be equal to the base URI
link : https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement
a quick javascript workaround would be to set src to null if it's value is empty
var src = $(this).prop('src') || null;
jsfiddle : http://jsfiddle.net/g9d8e4wh/1/
concerning your .attr() vs .prop() concern, I suggest you to head on there
.prop() vs .attr()
When SRC is empty, $(this) retuns the IMG object and src returns the objects context and baseURI. You can see it by viewing the object properties in the console:
$('img').click(function () {
alert($(this).prop('src'))
console.log($(this));
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With