nSticky/static variable references in for loops

Posted by pthulin on Stack Overflow See other posts from Stack Overflow or by pthulin
Published on 2010-04-03T09:26:45Z Indexed on 2010/04/03 10:03 UTC
Read the original article Hit count: 307

Filed under:
|

In this example I create three buttons 'one' 'two' 'three'. When clicked I want them to alert their number:

<html>
    <head>
        <script type="application/javascript" src="jquery.js"></script>
        <script type="application/javascript">
            $(document).ready(function() {
                var numbers = ['one', 'two', 'three'];
                for (i in numbers) {
                    var nr = numbers[i];
                    var li = $('<li>' + nr + '</li>');
                    li.click(function() {
                        var newVariable = String(nr);
                        alert(i); // 2
                        alert(nr); // three
                        alert(newVariable); // three
                        alert(li.html()); // three
                    });
                    $('ul').append(li);
                }
            });
        </script>
    </head>
    <body>
        <ul>
        </ul>
    </body>
</html>

The problem is, when any of these are clicked, the last value of the loop's variables is used, i.e. alert box always says 'three'.

In JavaScript, variables inside for-loops seem to be 'static' in the C language sense. Is there some way to create separate variables for each click function, i.e. not using the same reference?

Thanks!

Edit:

The solution is to use jQuery.data to associate arbitrary data with each element:

<html>
    <head>
        <script type="application/javascript" src="jquery.js"></script>
        <script type="application/javascript">
            $(document).ready(function() {
                var numbers = ['one', 'two', 'three'];
                for (i in numbers) {
                    var nr = numbers[i];
                    var li = $('<li>' + nr + '</li>');
                    li.data('nr', nr);
                    li.click(function() {
                        alert($(this).data('nr'));
                    });
                    $('ul').append(li);
                }
            });
        </script>
    </head>
    <body>
        <ul>
        </ul>
    </body>
</html>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery