jQuery prevAll()
方法是 jQuery 的内置函数,它返回所选元素的所有先前兄弟节点。此方法与 DOM 元素的先前兄弟一起向后遍历。
语法
selector.prevAll( filter )
filter:可选参数,该参数指定一个选择器表达式,以缩小对先前兄弟的搜索范围。如果我们要返回多个兄弟节点,我们可以用逗号分隔每个表达式。例子
看下面的理解理解jQuery prevAll() 方法的使用原理。
例1
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
function fun(){
$(document).ready(function(){
$("p").prevAll().css({"color": "blue", "border": "3px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div
<ul> ul </ul>
<h2> h2 </h2>
<p> p1 </p>
<p> p2 </p>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
效果如下:例2
使用过滤条件,找到h2元素上面的所有p元素。
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
function fun(){
$(document).ready(function(){
$("h2").prevAll("p").css({ "color": "blue", "border": "3px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div
<p> p1 </p>
<span> span </span>
<p> p2</p>
<ul> ul </ul>
<p> p3 </p>
<h2> h2 </h2>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
例3
使用过滤条件
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
border: 2px solid black;
padding: 10px;
margin: 15px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
function fun(){
$(document).ready(function(){
$("h2").prevAll("p").css({ "color": "blue", "border": "4px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div
<div> div <p> p </p> </div>
<span> span </span>
<p> p </p>
<p> p </p>
<h2> h2 </h2>
</div>
<button onclick = "fun()">点击看看 </button>
</body>
</html>