Burhan Mughal
Burhan Mughal

Reputation: 818

Issue in Loop calling

I am working in JavaScript. I have an issue with loop calling.
My code is :

Here is My Array

picArray = []; // Have tried with this too var picArray = new Array();

Here is My onClick function:

handler:function(){
    for(var i = 1; i<picArray.length; i++) {
        alert(picArray[i]);
    }
}

This is my loop to print the values from an array. And my Array is:

var imgSource = document.getElementById(hellow).src;
picArray[hellow] = imgSource;

This array is getting data on a condition. Handler function is called on click of a Button called Upload. The problem is When I press the Upload button it prints the correct values and remain pressed and print the values again. Is there any mistake in my code which compelling the loop to print values for 2 times?
Or anything else is doing this?

Upvotes: 3

Views: 97

Answers (3)

Endre Simo
Endre Simo

Reputation: 11541

I think you should consider using a closure function on clicking the button, for retaining the scope of the outer context. My supposition is that the root of the problem relays on the fact, that when you are entering the loop condition, you are getting the final value only when the loop has finished.

This problem can be solved by creating a function and calling it on each iteration of the loop, while passing i; calling the function will form a brand new execution context where the value of i is retained and can be used in any way within that context, including within the returned function.

Because you didn't post the rest of the code, i only suppose that's the problem. For solving this problem, here is the code i would use on this context:

function handler(n) {
    return function() {
        alert( 'You clicked on: ' + n );
    };
}

for (var i = 0; i < picArray.length; ++i) {
    picArray[i].onclick = handler(i);
}

...or another more elegant way:

for (var i = 0; i < picArray.length; ++i) {
    picArray[i].onclick = (function(n) {
        return function() {
            alert( 'You clicked on: ' + n );
        };
    })(i);
}

Upvotes: 1

ATOzTOA
ATOzTOA

Reputation: 36000

You should use event.preventDefault() to stop the button from firing.

Upvotes: 1

laurent
laurent

Reputation: 90834

It looks like an associative array (since hellow is both an element ID and array key) but you are accessing it like an indexed array.

So you should do this instead:

for (var key in picArray) {
    alert(picArray[key]);
}

Upvotes: 1

Related Questions