<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder;cursor:pointer; }
.blue { color:blue; }
.highlight { background:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="blue">Click to toggle (<span>clicks: 0</span>)</p>
<p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
<p class="blue">on these (<span>clicks: 0</span>)</p>
<p class="blue">paragraphs (<span>clicks: 0</span>)</p>
<script>
var count = 0;
$("p").each(function() {
var $thisParagraph = $(this);
var count = 0;
$thisParagraph.click(function() {
count++;
$thisParagraph.find("span").text('clicks: ' + count);
$thisParagraph.toggleClass("highlight", count % 3 == 0);
});
});
</script>
</body>
</html>
My problem is function assigned to click event of all the paragraph elements are closure. So on click on the first paragraph element the var counter increases. When the user clicks on the second paragraph the counter variable should display 2, isn’t it? But it is displaying 1.i m interested on why this is happening
You have defined
var counttwice. Leave out the one INSIDE the$("p").each(function(){...}). Thatvarinside there makes the variable local to that function.