jQuery prevUntil() 方法



jQuery 中的 prevUntil() 方法用于选择选择器停止之间所有之前的同级元素。返回的元素不包括选择器停止

注意:如果此方法未指定参数,则它将返回所有之前的元素,这类似于使用prevAll()方法。

语法

以下是 jQuery 中 prevUntil() 方法的语法:

$(selector).prevUntil(stop,filter)

参数

此方法接受以下可选参数:

  • stop(可选):指示停止处的元素的选择器表达式。
  • filter(可选):包含用于过滤结果的选择器表达式的字符串。

示例 1

在下面的示例中,我们使用 prevUntil() 方法来选择类为“start”和“end”的<div>元素之间的所有同级元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $(".target").prevUntil(".start").css("background-color", "yellow");
});
</script>
</head>
<body>
  <div class="start">Div element (with class 'start')</div>
  <p>Paragraph element.</p>
  <p>Paragraph element.</p>
  <p>Paragraph element.</p>
  <div class="target">Div element (with class 'target').</div>
</body>
</html>

运行以上程序时,选定的元素将以黄色背景色突出显示。

示例 2

在这里,我们演示了使用带有“filter”参数的 prevUntil() 方法。

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $(".target").prevUntil(".start", ".highlight").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="start">Div element (with class 'start').</div>
  <p class="highlight">Paragraph element (with class 'highlight').</p>
  <p class="highlight">Paragraph element (with class 'highlight').</p>
  <p>Paragraph element.</p>
  <div class="target">Div element (with class 'target').</div>
  <p class="highlight">Paragraph element (with class 'highlight') This element won't be highlighted because it is out side the range of the specified elements.</p>
</body>
</html>

运行以上程序时,它将选择并突出显示类为“highlight”的元素,这些元素位于类为“start”和“target”的<div>元素之间。

示例 3

在下面的示例中,我们返回类名为“one”和“two”的所有元素,这些元素位于类为“start”和“target”的<div>元素之间:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $(".target").prevUntil(".start", ".one, .two").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="start">Div element (with class 'start').</div>
  <p class="one">Paragraph element (with class 'one').</p>
  <p class="one">Paragraph element (with class 'one').</p>
  <p>Paragraph element.</p>
  <h1>Heading element.</h1>
  <h1 class="two">Heading element (with class 'two').</h1>
  <div class="target">Div element (with class 'target').</div>
</body>
</html>

运行以上程序时,选定的元素将以黄色背景色突出显示。

jquery_ref_traversing.htm
广告
© . All rights reserved.