I have a small script which makes an li element click-able and sets the location to that of a link inside of the li. This runs without error and my two console.log() calls are reporting back what I would expect, however, when you click on the li (whichever li) you are taken the href of the link in the last li. This doesn’t make much sense to me as I thought I had properly handled the scope.
Please correct my understanding and let me know where I went wrong.
JavaScript:
$(".homeCTA li").each(function(){
$href = $(this).find("a").attr("href");
console.log($(this)); // displays the expected selector
console.log($href); // displays the correct href
$(this).click(function(){ window.location = $href }); // this is overriding all of the previous passes
});
HTML:
<ul class="homeCTA">
<li class="left">
<img src="first-source.jpg">
<h2><a href="SearchResults.asp?Cat=1833">Yada Yada Yada</a></h2>
</li>
<li class="right">
<img src="second-source.jpg">
<h2><a href="SearchResults.asp?Cat=1832">Try the bisque</a></h2>
</li>
</ul>
Prefix
$hrefwithvar, so that the variable remains local.Currently, you’re overwriting a
$hrefvariable which keeps getting overwritten in the loop.Instead of looping over the list items, you can also use the following code: