<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>toggleClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
cursor: pointer;
}
.blue {
color: blue;
}
.highlight {
background: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click to toggle (<span>clicks: 0</span>)</p>
<p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
<p>on these (<span>clicks: 0</span>)</p>
<p>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>
如果把JQ代码换成如下的话 运行效果完全不一样了
<script>
var count = 0;
$( "p" ).each(function() {
var count = 0;
$( "p" ).click(function() {
count++;
$( "p" ).find( "span" ).text( "clicks: " + count );
$( "p" ).toggleClass( "highlight", count % 3 === 0 );
});
});
</script>
特别想知道 类似这种$name=$(this)的情况 不是把name 封装成就近的this的jq对象吗 方便之后引用属性
为什么两个代码的运行结果不一样 难道是each的问题 求详细each的用法
柠檬酸钠
相关分类