Suzanne Edelman Creoconcept Suzanne Edelman Creoconcept - 5 months ago 31
jQuery Question

jquery - reload function, lose variable value

lets say i have this function:

$("#click").click(function myFunction(){
var id = $(this).attr("id");
myFunction();
});


Now, obviously, after the click event, id == "click", but when the function reloads, id == undefined.
Is there a way that i can reload the function without redefining the variable?

Answer

You're recursively calling a closure function. Here's a working copy where you can use a callback function to access the variable:

$("#click").click(function() {
   var id = $(this).attr("id");
   console.log("click id: " + id);
   myFunction(id);
});

function myFunction(id) {
   console.log("id: " + id);
}

JSFiddle Example