How to store local variables in jQuery click functions?

Posted by Geuis on Stack Overflow See other posts from Stack Overflow or by Geuis
Published on 2009-09-28T07:05:05Z Indexed on 2010/05/21 8:20 UTC
Read the original article Hit count: 249

Filed under:
|
|
|

I'm trying to figure out how to store external variable values in the functions created during jQuery's click() event. Here's a sample of the code I'm working with now.

for(var i=0; i<3; i++){
	$('#tmpid'+i).click(function(){
		var gid = i;
		alert(gid);
	});
}

<div id="tmpid0">1al</div>
<div id="tmpid1">asd</div>
<div id="tmpid2">qwe</div>

So what's happening is that the events are attaching properly, but the value of 'gid' is always the last incremented value of 'i'. I'm not sure how to setup the private variable in this situation.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about variables