Sunday 23 October 2016

javascript - how to return two functions for onclick event











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 :)


Answer



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);
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...