jQuery nextAll() 方法



jQuery 中的 nextAll() 方法用於選擇所有在選定元素之後出現的同級元素。

同級元素是指屬於同一個父元素的元素。換句話說,具有相同父元素的元素是同級元素。

此方法遍歷同級元素,從緊隨其後的同級元素開始,一直持續到選定元素父元素的末尾。

語法

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

$(selector).nextAll(filter)

引數

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

  • filter: 用於過濾下一個同級元素的選擇器表示式。它將搜尋範圍縮小到匹配特定條件,例如類、ID、元素型別等。

示例 1

在以下示例中,我們使用 nextAll() 方法返回 <div> 的所有同級元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("div").nextAll().css("background-color", "#40a944");
      });
  </script>
</head>
<body>
  <div>This is (div) element.</div>
  <p>This is paragraph 1</p>
  <p>This is paragraph 2</p>
  <p>This is paragraph 3</p>
  <p>This is paragraph 4</p>
  <p>This is paragraph 5</p>
</body>
</html>

當我們執行上述程式時,nextAll() 方法選擇 <div> 元素下的所有元素,並將它們的背景更改為綠色。

示例 2

在下面的示例中,我們從類名為 'demo' 的 "<p> 元素中返回類名為 "one" 的同級元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("p.demo").nextAll(".one").css("background-color", "#40a944");
      });
  </script>
</head>
<body>
  <div>This is div element.</div>
  <p>paragraph 1</p>
  <p class="demo">paragraph 2 (class: demo) - Parent</p>
  <p class="one">paragraph 3 (class: one)</p>
  <p>paragraph 4</p>
  <p class="one">paragraph 5 (class: one)</p>
  <p class="one">paragraph 6 (class: one)</p>
  <p>paragraph 7</p>
</body>
</html>

當我們執行上述程式時,nextAll() 方法選擇類名為 'demo' 的 "<p> 元素下所有類名為 "one" 的元素,並將它們的背景更改為綠色。

示例 3

在這裡,我們返回所有類名為 "one"、"two" 和 "three" 的元素,它們是類名為 'demo' 的 "<p> 元素的同級元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("p.demo").nextAll(".one, .two, .three").css("background-color", "#40a944");
      });
  </script>
</head>
<body>
  <div>This is div element.</div>
  <p>paragraph 1</p>
  <p class="demo">paragraph 2 (class: demo) - Parent</p>
  <p class="one">paragraph 3 (class: one)</p>
  <p>paragraph 4</p>
  <p class="two">paragraph 5 (class: two)</p>
  <p class="three">paragraph 6 (class: three)</p>
  <p class="three">paragraph 7 (class: three)</p>
  <p>paragraph 8</p>
</body>
</html>

執行上述程式後,它將選擇類名為 'demo' 的 "<p> 元素下所有類名為 "one"、"two" 和 "three" 的元素,並將它們的背景更改為綠色。

jquery_ref_traversing.htm
廣告

© . All rights reserved.