$(selector).each()
来源:互联网 发布:sql server 类型转换 编辑:程序博客网 时间:2024/06/15 16:44
.each( function(index, Element) )返回: jQuery
描述: 遍历一个jQuery对象,为每个匹配元素执行一个函数。
添加的版本: 1.0.each( function(index, Element) )
- function(index, Element)类型: Function()为每个匹配元素执行的一个函数。
.each()
方法用来让DOM循环结构更简单更不易出错。它会迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。更重要的是,回调函数是在当前DOM元素为上下文的语境中触发的。因此关键字 this
总是指向这个元素。
假设页面上有这样一个简单的无序列表。
<ul> <li>foo</li> <li>bar</li></ul>
你可以选中并迭代这些列表:
$( "li" ).each(function( index ) { console.log( index + ": "" + $(this).text() );});
列表中每一项会显示在下面的消息中:
0: foo
1: bar
我们可以通过返回 false
以便在回调函数内中止循环。
注意: jQuery的方法,返回一个jQuery对象遍历jQuery集合中的元素 - 被称为隐式迭代的过程。当这种情况发生时,它通常不需要显式地循环的.each()
方法:
// The .each() method is unnecessary here:$( "li" ).each(function() { $(this).addClass( "foo" );}); // Instead, you should rely on implicit iteration:$( "li" ).addClass( "bar" );
例子:
<!DOCTYPE html><html><head> <style> div { color:red; text-align:center; cursor:pointer; font-weight:bolder; width:300px; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script></head><body> <div>Click here</div> <div>to iterate through</div> <div>these divs.</div><script> $(document.body).click(function () { $( "div" ).each(function (i) { if ( this.style.color != "blue" ) { this.style.color = "blue"; } else { this.style.color = ""; } }); });</script> </body></html>
案例二:
使用 'return' 来提前结束 each() 循环
<!DOCTYPE html><html><head> <style> div { width:40px; height:40px; margin:5px; float:left; border:2px blue solid; text-align:center; } span { color:red; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script></head><body> <button>Change colors</button> <span></span> <div></div> <div></div> <div></div> <div></div> <div id="stop">Stop here</div> <div></div> <div></div> <div></div><script> $( "button" ).click(function () { $( "div" ).each(function ( index, domEle) { // domEle == this $( domEle ).css( "backgroundColor", "yellow" ); if ( $(this).is( "#stop" ) ) { $( "span" ).text( "Stopped at div index #" + index ); return false; } }); }); </script> </body></html>
0 0
- $(selector).each()
- [JS] $.each(), $(selector).each()
- $.each()与$(selector).each()
- $.each()与$(selector).each()
- $.each 与$(selector).each()
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each 和$(selector).each()的区别
- $.each()与$(selector).each()区别详解
- $(selector).each()和$.each()的区别
- $.each()与$(selector).each()区别详解
- $.each()与$(selector).each()区别详解
- 推箱子
- Android Framework:Binder(2)-Service Manager
- 告知你不为人知的UDP-疑难杂症和使用
- jsp+servlet 练习
- Spring(一)——总体介绍
- $(selector).each()
- 同步容器和并发容器
- JAVA Comparator和Comparable的区别
- jquery子元素过滤器
- 66 Plus One
- csu1093: Caps Lock 模拟水题
- python 基础 —— platform 模块
- 我们真正该关注的应该是产品开发的效率与质量, 而不是工程实践或敏捷的价值
- c