I'm trying to console log an image source using $(this).find('img').attr('src');
Here is my HTML
<div id="container">
<div id="stage">
<div id="gallery">
<img class="photo" src="_images/image#1" />
<img class="photo" src="_images/image#2" />
<img class="photo" src="_images/image#3" />
<img class="photo" src="_images/image#4" />
</div>
</div>
</div>
Here is my JS
function grabIt(){
var thisImageSrc = $(this).find('img').attr('src');
}
console.log(thisImageSrc)
$('#gallery img').mouseover(grabIt);
I'll be using the img source within a larger function which is outside the scope of this question. My goal is to grab the image source when mousing over an image.
I'm new to jQuery and it would be easier for me to understand the long form of the answer code instead of functions nested inside of functions - if possible.
thank you!
Put the console.log
statement inside the function. thisImageSrc
doesn't exist outside of grabIt
and console.log
is called before grabIt
has ever been executed.
Also, since you bind the event handler to the image itself, $(this).find('img')
will return an empty set. An image cannot contain another image. Access the src
property on the element itself.
So, fixing both things, you end up with
function grabIt(){
var thisImageSrc = this.src;
console.log(thisImageSrc)
}
$('#gallery img').mouseover(grabIt);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.