user5489593
user5489593

Reputation:

Value of clicked element function argument is wrong

I have a loop (from 0 to 5) that add onclick event for each element that is in a <nav>.

<nav class="mq-ui-bg tools-bar" style="top:70px;left:20px;width:65px;height:385px;">
<div class="container">
    <div class="tool selected"><div class="pa" style="background-image:url('Images/Icon/Cursor.png');"></div></div>
    <div class="tool"><div class="pa" style="background-image:url('Images/Icon/Select1.png');"></div></div>
    <div class="tool"><div class="pa" style="background-image:url('Images/Icon/Bucket.png');"></div></div>
    <div class="tool"><div class="pa" style="background-image:url('Images/Icon/Rect1.png');"></div></div>
    <div class="tool"><div class="pa" style="background-image:url('Images/Icon/Circle1.png');"></div></div>
    <div class="tool"><div class="pa" style="background-image:url('Images/Icon/Erase.png');"></div></div>
    </div>
</nav>

Inside its onclick event is called a function with an argument, which contains the number of element's position in this nav that I added above.

The code of them is very short:

function FixTools(){
    var elqry=ElementClass('tools-bar').getElementsByClassName('tool');
    for(var i=0;i<elqry.length;i++){
        elqry[i].children[0].onclick=
        function(){
                SelectTool(i)
        };
    }
    function SelectTool(n){
        er=ElementClass('tools-bar').getElementsByClassName('tool');
        function fu1(i){
                Attribute( /* This changes the class attribute */
                    er[i],
                    'class',
                    'tool '+
                    ((i==n)?'selected':'un')
                    /* If i value is equal to clicked element position number
                    in my nav, then it will be selected */
                );
        }
        for(var i=0;i<er.length;i++){
                fu1(i);
                /* This loop should unselect all elements
                that are not from n position number in my nav*/
        }
        delete er;
    }
}

FixTools();

So my problem is because in my FixTools() function, into the first loop, into the onclick event and into the SelectTool(i) function first argument I only receive a integer, this: 6, the number six.

What am I doing wrong?

Upvotes: 0

Views: 32

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382168

due to a mis-click, I can't close as duplicate, so here's a fix

This is a classical problem : by the time your callbacks are called, i has the value of end of loop.

for(var i=0;i<elqry.length;i++){
     (function(i){
        elqry[i].children[0].onclick=
        function(){
                SelectTool(i)
        };
     })(i);
}

The idea here is to wrap the loop body in a function creating a scope in which the value of i at function call time is saved.

Upvotes: 1

Related Questions