jQuery prev() 方法用于获取同级兄弟节点的上一个元素。此方法与 DOM 元素的前一个兄弟元素一起向后遍历。
语法
selector.prev( selector )
selector:可选参数,该参数用于指定一个选择器表达式,以缩小对前一个兄弟的搜索范围。例子
例1
找到p元素的上一个元素是h2元素。
<!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").prev().css({ "font-size": "30px", "color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div
<ul> ul </ul>
<h2> h2 </h2>
<p> p </p>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
例2
<!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").prev("p").css({ "color": "blue", "border": "5px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div
<ul> ul </ul>
<h2> h2 </h2>
<p> p </p>
<h2> h2 </h2>
<span> span </span>
<h2> h2 </h2>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
例3
循环查找上一个元素
<!DOCTYPE html>
<html>
<head>
<style>
div {
display: block;
width: 50px;
height: 50px;
font-size: 20px;
margin: 10px;
border: 2px solid black;
float: left;
}
p {
clear: left;
margin: 10px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
$(document).ready(function(){
var current = $("#d5");
current.css( "background-color", "red");
$("button").click(function(){
current = current .prev();
$("div").css("background", "");
current.css( "background-color", "red" );
});
});
</script>
</head>
<body>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div id = "d5"> </div>
<p> 点击下面的按钮查看效果。 </p>
<p>
<button> 点击看看 </button>
</p>
</body>
</html>