Passed by reference in an .each loop

Passed by reference in an .each loop

I've made a trivial html page to show my problem.  This page should take all of the <tr> tags from the first table, move them into the second table in reverse order, and change each <tr> tag's click handler to print it's internal <td> tag's contents.

Unfortunately, the function I've set as the click handler seems to be passing a variable by reference rather than by value.  I'm sure this is probably the expected behavior, but is there someway to prevent this behavior?

If this doesn't sound very clear, hopefully the code I've included will make more sense:

  1. <html>

    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script>
    $(document).ready( function() {

        // Loop through each <tr> in the first table, and move it in reverse order to the second table
        $('#first > tbody > tr').each( function() {
       
            // Store the value inside the <td> tag
            string = $(this).find( 'td' ).text();
           
            // Move the <tr> tag
            $("#second").prepend( $(this) );
           
            // This should print out the text inside the <td> tag when you click on the new <tr>
            // It should only add to the first <tr> tag, i.e. the one we just added
            $("#second").find('tr:first').bind( 'click', function() { alert( string ); } );
        });
       
        // Now, every time you click on a row, you will get 53.  Why?
        string = 53;
       
    });
    </script>
    </head>

    <body>

        <p>First table</p>

        <table id="first">
            <tr><td>Row 1</td></tr>
            <tr><td>Row 2</td></tr>
            <tr><td>Row 3</td></tr>
        </table>
       
        <p>Second table</p>

        <table id="second">
            <tr><td>Last row</td></tr>
        </table>
    </body>

    </html>












































Thanks,

Gary