There's no way that calling cap_check
will ever alert anything other than undefined
. A function is not a static object. When you call a function, it creates a new instance on the internal stack. row
will be initialized as undefined
and a new click handler will be bound to td
elements (also not likely to be useful - as another duplicate event handler will be bound each time you call cap_check
).
Most likely, you want something like this:
var cap_check=(function() {
var row;
$('td').change(function(){
row = $(this).parent().parent().children().index($(this).parent());
alert(row);
});
return function() {
alert(row);
};
}());
This is a self-executing function. When the script runs, the part of the function BEFORE the "return" is executed immediately, creating your event binding once, and returning a function that references the original function instance. This creates a closure which means that the function maintains a reference to the objects of it's parent (in this case, the row
variable). So your event handler, and the function returned as cap_check
, now will always refer to the same instance of row
.
So - now any code that calls cap_check
will always return the same value assigned as a result of the change
event.
Fiddle:
http://jsfiddle.net/RagUe/5/
(Note that I changed the event to "click" instead of "change" to make it easily testable).