0

I have 3 spans, valued 0, 1, and 2. When you click on one, I want to alert its value. With my current code, they all alert "length." I don't know what I'm doing wrong

<style>
.text{
    width:20px;
    height:20px;
    border:1px solid black;
}
</style>

<span class='text'>0</span>
<span class='text'>1</span>
<span class='text'>2</span>

<script>
var textSpans=document.querySelectorAll('span.text');
for (i in textSpans)
{
    textSpans[i].onclick=function() {alert(i);};   
}
</script>

here is a fiddle

chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • 2
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Xotic750 Apr 20 '14 at 23:49

2 Answers2

0

Use this:

var textSpans = document.querySelectorAll('span.text');

for (i in textSpans) {
    textSpans[i].onclick = function(e) {
        alert(e.target.innerHTML);
    };   
}

The variable e is the mouse event. This will alert the contents of the target element of the click.

JSFiddle

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
0

The reason your code is not working, is because you are not using closure.

A closure is the local variables for a function - kept alive after the function has returned. So, in your original example, the last "i" left in the function scope is a "2". SO, to create a "closure" around each iteration of the "i", try using an anonymous function to "enclose/closure" the variable..

http://jsfiddle.net/bP88Z/4/

/* not a fan of 'i in ..." with arrays

An array is iterated using:

for (var i = 0; i < a.length; i++)
   //do stuff with a[i]

An object being used as an associative array is iterated using:

for (var key in o)
 do stuff with o[key] */

var textSpans=document.querySelectorAll('span.text');
for (i=0;i<textSpans.length;i++)
{
    (function(v){
        textSpans[v].onclick=function() {alert(v);};  
    }(i));
}
james emanon
  • 11,185
  • 11
  • 56
  • 97