html - Getting the correct href of the clicked link with javascript? -


this question has answer here:

i have simple html menu:

<div id="menulinks">   <ul>     <li><a href="#link1">link 1</a></li>     <li><a href="#link2">link 2</a></li>     <li><a href="#link3">link 3</a></li>     <li><a href="#link4">link 4</a></li>   </ul> </div> 

and need write javascript - can't use jquery - gives me href of clicked anchor link. that's did:

var = document.getelementbyid("menulinks").getelementsbytagname("a"); ( var o = 0; o < a.length; o++ ) {   var clickedlink = a[o];   clickedlink.addeventlistener("click", function() {     var b = clickedlink.getattribute("href");     alert(b);   }); } 

it works, '#link4' answer in alertbox, no matter link click. can tell me, what's wrong? in advance!

your problem clickedlink getting overwritten subsequent value each time for loop iterates , time link clicked, clickedlink has been assigned last href value.

i'm guessing confusion results assuming javascript has block scoping when uses lexical scoping. (you might read on variable hoisting too...)

one solution bind each value assigned clickedlink invoked function...

for ( var o = 0; o < a.length; o++ ) {   var clickedlink = a[o];   (function(clickedlink) {      clickedlink.addeventlistener("click", function() {       var b = clickedlink.getattribute("href");       alert(b);     });   })(clickedlink); } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -