S.Hagvin S.Hagvin - 6 months ago 16
Javascript Question

How can I create function which will return value of jQuery method attr

I have html structure:

<div>
<ul>
<li><img src="img/product1.png" alt="product1"></li>
<li><img src="img/product2.png" alt="product2"></li>
<li><img src="img/product3.png" alt="product3"></li>
<li><img src="img/product4.png" alt="product4"></li>
</ul>
</div>


and I have done attempt create function which will get attribute of current img element and I want to return from this function this current attribute, I have next code:

var sr = "";
function imgSrc(){
$('div').on("click", "ul li img", function () {
sr = $(this).attr("src");
return sr;
});
}

console.log(imgSrc());


unfortunately I get undefined in my console.

Answer

Your function doesn't return anything. It just defines an onClick handler. So that's why you get a return value of 'undefined'

If your intention is to log the src of a div when you click on it, your code would need to be more like this...

$('div').on("click", "ul li img", function () 
{
    var sr = $(this).attr("src");
    console.log(sr);
});

That registers the event listener on the element.

However, if you want to wrap the listener in a function and then call that function, as you have done, that will also work - the function in the on("click") will be triggered when clicking an element. The value of sr will be set, but the outer function itself won't return a value. You would need to find another way to do something with the value of sr, within the function in the on("click")

Comments