1.$(selector).each()
主要对DOM的遍历
$(selector).each(function(index,element)){
//index - 选择器的 index 位置 从0开始
//element - 当前的选择器(也可使用 “this” 选择器)
}
$(“button”).click(function(){
KaTeX parse error: Expected '}', got 'EOF' at end of input: …n(){ alert((this).text())
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="javascript/jquery-3.3.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>
2.$.each
遍历对象或数组
$.each(Array, function(i, value) {
this; //this指向当前元素
i; //i表示Array当前下标
value; //value表示Array当前元素
});
$.each(Object, function(name, value) {
this; //this指向当前属性的值
name; //name表示Object当前属性的名称
value; //value表示Object当前属性的值
});
3.find()
find() 方法获得当前元素集合中每个元素的后代
//搜索所有段落中的后代 span 元素,并将其颜色设置为红色:
$(“p”).find(“span”).css(‘color’,‘red’);
4.siblings()
siblings() 获得匹配集合中每个元素的同胞
//查找每个 p 元素的所有类名为 “selected” 的所有同胞元素:
$(“p”).siblings(".selected")