I need to get the row number out of a JavaScript function:
function cap_check(){
var row;
$('td').change(function(){
row = $(this).parent().parent().children().index($(this).parent());
alert(row);
});
alert(row);
}
Within the function, row is correctly alerted. Outside of the function, it is undefined.
There’s no way that calling
cap_checkwill ever alert anything other thanundefined. A function is not a static object. When you call a function, it creates a new instance on the internal stack.rowwill be initialized asundefinedand a new click handler will be bound totdelements (also not likely to be useful – as another duplicate event handler will be bound each time you callcap_check).Most likely, you want something like this:
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
rowvariable). So your event handler, and the function returned ascap_check, now will always refer to the same instance ofrow.So – now any code that calls
cap_checkwill always return the same value assigned as a result of thechangeevent.Fiddle:
http://jsfiddle.net/RagUe/5/
(Note that I changed the event to “click” instead of “change” to make it easily testable).