<!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>
我的问题是分配给所有段落元素的单击事件的函数都是关闭的。因此,单击第一个段落元素时,var 计数器会增加。当用户单击第二段时,计数器变量应该显示 2,不是吗?但它显示 1.im 对为什么会发生这种情况感兴趣