Understanding $.each and stored variables
Hi, I need to iterate over a list of elements and I want to store variables within the $.each-section for later use in some functions.
Now I have a problem to understand why the variable $this of my function "doFunction()" returns always the last element while $(this) in the click-handler returns the right clicked element.
I thought that defined variables in the $.each-Method are like closures - and separate within each iteration.
Are you able to explain me how the whole thing works? Here's the code:
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript" language="javascript">
jQuery(function($){
$("li").each (function() {
var $this = $(this);
// a click on a li-element returns the right stored $this
$this.click(function(){
console.log( "$this.text() = ", $this.text() );
doFunction();
return false;
});
// $this in doFunction() returns always the last li-element
doFunction = function(){
console.log( "doFunction(): $this.text() =", $this.text() );
};
});
});
</script>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>