jQuery prevUntil() 方法



jQuery 中的 prevUntil() 方法用於選擇選擇器停止之間所有之前的同級元素。返回的元素不包括選擇器停止

注意:如果此方法未指定引數,則它將返回所有之前的元素,這類似於使用prevAll()方法。

語法

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

$(selector).prevUntil(stop,filter)

引數

此方法接受以下可選引數:

  • stop(可選):指示停止處的元素的選擇器表示式。
  • filter(可選):包含用於過濾結果的選擇器表示式的字串。

示例 1

在下面的示例中,我們使用 prevUntil() 方法來選擇類為“start”和“end”的<div>元素之間的所有同級元素:

<html>
<head>
<script src="https://code.jquery.com/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.jquery.com/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.jquery.com/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
廣告