1

Possible Duplicate:
How do I pass the value (not the reference) of a JS variable to a function?

i have several links (var a[]) with an onclick event on them. this works well so far by using one function:

function setCurrentImage(x) {
    return function() {
        alert("Image: "+x);
        return false;
    }
}

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

the thing is, i need two functions. and this code just won't work:

function setCurrentImage(x) {
    return function() {
        alert("Image: "+x);
    }
}

function setCurrentNote(x) {
    return function() {
        alert("Note: "+x);
    }
}

for(var i = 0; i < a.length; i++) {
    a[i].onclick = function() {
        setCurrentImage(i);
        setCurrentNote(i);
        return false;
    }
}

what is wrong with this code? thanks in advance :)

Community
  • 1
  • 1
Julson Moser
  • 15
  • 1
  • 3

2 Answers2

3

Each of the functions that you call returns a function, but doesn't actually do anything.
You never call the functions that they return.

Once you fix that, you'll have another problem; all of your inline handlers share the same i variable.
You need to wrap that in an IIFE.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

To extend SLaks's answer:

function setCurrentImage(x) {
    alert("Image: "+x);
}

function setCurrentNote(x) {
    alert("Note: "+x);
}
function setOnclickHandler(x) {
    return function() {
        setCurrentImage(x);
        setCurrentNote(x);

        return false;
    };
}

for(var i = 0; i < a.length; i++) {
    a[i].onclick = setOnclickHandler(x);
}
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123