<!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的用法
                    
                    
                1 回答
 
                    
                    
                            柠檬酸钠
                            
                                
                            
                        
                        
                                                
                    TA贡献331条经验 获得超534个赞
each是遍历jquery对象的方法,接收一个回调函数作为参数,回调函数可以接收索引(index)和当前便利的元素(el)两个参数,其中el和$(this)等效。而$("p")是选择所有的p元素,$(this)只代表当前的元素,所以肯定不一样
- 1 回答
- 0 关注
- 1288 浏览
添加回答
举报
0/150
	提交
		取消
	