jQuery nextUntil() 方法用于搜索指定元素直到xx元素停止的所有元素。

如果 selector 未提供或不匹配,则 nextUntil() 方法将返回所有下一个兄弟元素,类似于 nextAll() 方法。

语法

$(selector).nextUntil(stop,filter) 

参数

  • stop: 这是一个可选参数。它可以是选择器表达式、jQuery 对象或指示在何处停止搜索的元素。
  • filter: 这是一个可选参数。它是一个缩小搜索范围的选择器表达式。

例子

1)搜索元素直到h3元素停止的所有元素。

<!DOCTYPE html>
<html>
<head>
<style>
.main * { 
  display: block;
  position: relative;
  border: 2px solid black;
  padding: 8px;
  margin: 10px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
function fun(){
$(document).ready(function(){
  $("h1").nextUntil("h3").css({ "color": "blue", "border": "3px solid blue"});
});
}
</script>
</head>
<body class = "main"> body
	<div id = "div1"> div element
	<h1>  h1 </h1>
	<h2>  h2 </h2>
	<ul> ul  </ul>
	<span> span </span>
	<p> p </p>
	<h3>  h3 </h3>
	</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>

2)搜索直到h3停止的所有span元素

 <!DOCTYPE html>
<html>
<head>
<style>
.main * { 
  display: block;
  position: relative;
  border: 2px solid black;
  padding: 8px;
  margin: 10px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
function fun(){
	$(document).ready(function(){
	  $("h1").nextUntil("h3", "span").css({ "color": "blue", "border": "3px solid blue"});
	});
}
</script>
</head>

<body class = "main"> body
<div id = "div1"> div 
<h1>  h1 </h1>
<p>  p </p>
<span> span </span>
<h4>  h4 </h4>
<span> span </span>
<h3>  h3 </h3>
<span> span </span>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
3)使用id过滤

 <!DOCTYPE html>
<html>
<head>
<style>
.main * { 
  display: block;
  border: 2px solid black;
  padding: 8px;
  margin: 10px;
}
</style>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
function fun(){
$(document).ready(function(){
  $("h1").nextUntil("h3", "#s2").css({ "color": "blue", "border": "3px solid blue"});
});
}
</script>
</head>

<body class = "main"> body
<div id = "div1"> div 
<h1>  h1 </h1>
<span id = "s1"> span  id = "s1" </span>
<span id = "s2"> span  id = "s2" </span>
<span id = "s3"> span  id = "s3" </span>
<h3>  h3 </h3>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>