prevAll() 方法
定义和用法
prevAll() 获得当前匹配元素集合中每个元素的前面的同胞元素,使用选择器进行筛选是可选的。
语法
.prevAll(selector)
參數
参数 | 描述 |
---|---|
selector | 字符串值,包含用于匹配元素的选择器表达式。 |
详细说明
如果给定一个表示 DOM 元素集合的 jQuery 对象,.prevAll() 方法允许我们在 DOM 树中搜索这些元素前面的同胞元素,并用匹配元素构造一个新的 jQuery 对象。
该方法接受可选的选择器表达式,与我们向 $() 函数中传递的参数类型相同。如果应用这个选择器,则将通过检测元素是否匹配该选择器对元素进行筛选。
栗子:
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
<script>
$('li.third-item').prevAll().css('background-color', 'red');
</script>
結果為:
栗子二:
<style>
div { width:70px; height:70px; background:#abc;
border:2px solid black; margin:10px; float:left; }
div.before { border-color: red; }
</style>
<script type="text/javascript" src="/jquery/jquery.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script>$("div:last").prevAll().addClass("before");</script>
結果為:
小練習:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<style>
.bar {
height:60px;
width:100%;
margin-top:60px;
}
.bar ul li {
width:120px;
list-style: none;
height:60px;
box-sizing:border-box;
text-align:center;
line-height:20px;
float: left;
}
.bar ul li .comm_red{
width:60px;
height:20px;
margin:0 auto;
}
.hs {
background:#949494;
}
.cj {
background:#7c97af;
}
.zj {
background:#d5b32a;
}
.gj {
background:#ec7e0f;
}
.mx {
background:#db7973;
}
.nd {
background:#8392da;
}
.zz {
background:#f181f8;
}
.color_com {
background:gray !important;
}
.com_sjx {
width: 0;
height: 0;
margin: auto;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
}
.bar ul li .hssjx{