首页 > Web开发 > 详细

Jquery中each

时间:2017-02-16 15:57:11      阅读:132      评论:0      收藏:0      [点我收藏+]

1、选择器+遍历

$(‘div‘).each(function (i){

   i就是索引值

   this 表示获取遍历每一个dom对象

});

 

2、选择器+遍历

$(‘div‘).each(function (index,domEle){

   index就是索引值

  domEle 表示获取遍历每一个dom对象

});

  1. 3、更适用的遍历方法  
  2. 1)先获取某个集合对象  
  3. 2)遍历集合对象的每一个元素  
  4. var d=$("div");  
  5. $.each(d,function (index,domEle){  
  6.   d是要遍历的集合  
  7.   index就是索引值  
  8.   domEle 表示获取遍历每一个dom对  
  9. });  

 

代码案例:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		*{margin:0;padding:0;}
		img{ display: block; }
		div{ width: 100px; height: 30px;line-height: 30px; text-align: center; border:1px solid red; margin-bottom: 10px; }
		.example{ border:1px solid red; width: 100px; height: 100px; }
		.btn{ margin-top: 20px; overflow: hidden; display: block; }
	</style>
	<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
	<script type="text/javascript">
		$(function(){
			//注意:此处 this 指代的是 DOM 对象而非 jQuery 对象。
			// $(‘img‘).each(function(i){
			// 	this.src="test"+i+‘.jpg‘;
			// })
			//如果你想得到 jQuery对象,可以使用 $(this) 函数。
			// $("img").each(function(){
			//   $(this).toggleClass("example");
			// });
              //使用 ‘return‘ 来提前跳出 each() 循环。 $("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> </head> <body> <p>each概述</p> <p>以每一个匹配的元素作为上下文来执行一个函数</p> <p>意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时, 都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整型)。返回‘false‘将停止循环(就像在普通 的循环中使用‘break‘)。返回‘true‘跳至下一个循环(就像在普通的循环中使用‘continue‘)。</p> <img /> <img /> <button class="btn">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> </body> </html>

  

Jquery中each

原文:http://www.cnblogs.com/huanghuali/p/6405847.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!