I am looping through a Javascript array, attaching events to elements by ID. I can see that the correct event is added, however, when I click on the links to trigger the event, they all display 'link6' was clicked, rather than the one I intended!
Below is a snippet that illustrates the problem.
I would be enormously grateful for an explanation of why this happens and how I should be coding to overcome this. I am guessing it is something to do with dynamic values being assigned, but my initial thoughts are that this doesn't seem to be behaving logically!
<html>
<body>
<p id='link1'>Link 1</p>
<p id='link2'>Link 2</p>
<p id='link3'>Link 3</p>
<p id='link4'>Link 4</p>
<p id='link5'>Link 5</p>
<p id='link6'>Link 6</p>
<script type='text/javascript'>
var sections = new Array('link1', 'link2', 'link3', 'link4', 'link5', 'link6');
for (var section in sections) {
console.log('Attaching event to ' + sections[section] );
document.getElementById(sections[section]).addEventListener('click', function(e){ alert('click '+sections[section]); });
}
</script>
</body>