Reputation: 581
I'm still learning and I have a little question.
I have three links and I want to know which link I gave click. So, this are my links:
<ul id="links">
<li><a id="map-1" href="#">Mapa 1</a></li>
<li><a id="map-2" href="#">Mapa 2</a></li>
<li><a id="map-3" href="#">Mapa 3</a></li>
</ul>
And this is my JS
var currentLink;
$(document).ready(function(){
$("#links a").each(function(){
$(this).on("click", function(e){
return currentLink= $(this).attr("id");
console.log(currentLink); //This works 'cause I know the ID of my current link
});
});
});
console.log(currentLink); //I lost the value of my link
Someone can explain what I'm missing? Thanks a lot!!
:)
Upvotes: 0
Views: 58
Reputation: 423
- Your question is not clear but here is what is happening
- You need to tell us what exactly you are looking for
See my comments near each line
/* Variable is defined here*/
var currentLink;
/*document ready, means this executes after your page is loaded and dom is ready*/
$(document).ready(function(){
$("#links a").each(function(){
$(this).on("click", function(e){
return currentLink= $(this).attr("id");
console.log(currentLink); /***This is wrong, not sure how it works, after you return something this line is not supposed to be executed.***/
});
});
});
//This gets executed immediately before document ready is ran, probably first
console.log(currentLink); //YOUR VALUE IS NEVER assigned here while it is executing
Upvotes: 2
Reputation: 60143
I hope this helps.
// This line runs first.
var currentLink;
$(document).ready(function () {
$("#links a").each(function () {
$(this).on("click", function (e) {
// This line runs third.
return currentLink = $(this).attr("id");
console.log(currentLink); // This never runs, since there's a "return" above it.
});
});
});
// This line runs second.
console.log(currentLink);
EDIT
To elaborate: first you create the variable. Then you set up a click handler. Then you log the value of the variable. Then sometime in the future, when someone clicks on a link, your click handler actually runs, and you assign a value to that variable (long after your console.log
executed).
Upvotes: -1