<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script>
</head>
<style>
div.kk { color:red; text-align:center; cursor:pointer;font-weight:bolder; width:300px; }
ul { font-size:18px; margin:0; }
span.tt { color:blue; text-decoration:underline; cursor:pointer; }
.example { font-style:italic; }
div.ww { width:40px; height:40px; margin:5px; float:left;
border:2px blue solid; text-align:center; }
span.ww { color:red; }
</style>
<body>
<ul>
<li>foo</li>
<li>bar</li>
<li>lala</li>
<li>cece</li>
</ul>
<hr />
<div class="kk">Click here</div>
<div class="kk">to iterate through</div>
<div class="kk">these divs.</div>
<hr />
To do list: <span class="tt">(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>
<hr />
<button>Change colors</button>
<span class="ww"></span>
<div class="ww"></div>
<div class="ww"></div>
<div class="ww"></div>
<div class="ww"></div>
<div id="stop" class="ww">Stop here</div>
<div class="ww"></div>
<div class="ww"></div>
<div class="ww"></div>
<script type="text/javascript">
/**
* .each(function(index,Element)) 返回jQuery
* 描述:遍历一个jQuery对象,为每个匹配元素执行一个函数
*
* function(index,Element)
* 类型:Function()
* 为每个匹配元素执行的一个函数
*
* */
/**
* .each()方法用来让DOM循环结构更简单更不易出错。
* 它会迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,
* 会传递当前循环次数作为参数(从0开始计数)。更重要的是,回调函数
* 是在当前DOM元素为上下文的语境中触发的。因此this总是指向这个元素。
*
* */
$(document).ready(function(){
//例子一
//遍历, 然后通过返回false来终止循环
$("li").each(function(suoyin){
console.log(suoyin + " :" + $(this).text() + "<br />");
if(suoyin >= 2) return false;
});
//例子二 : 遍历三个div并设置它们的color属性
$(document.body).click(function(){
$("div").each(function(i){
if(this.style.color != "blue"){
this.style.color = "blue";
}else{
this.style.color = "";
}
});
});
//例子三:
$("span").click(function(){
$("li").each(function(j){
$(this).toggleClass("example");
if($(this).is(".example")) this.style.color = "blue";
if(j >= 2) {
return false;
}
});
});
//例子四:
$("button").click(function(){
$("div").each(function(index,domEle){
$(domEle).css("background-color","yellow");
if($(this).is("#stop")){
$("span").text("stop at : " + index);
return false;
}
});
});
});
</script>
</body>
</html>