jQuery 元素 + next 選擇器



jQuery 中的元素 + next 選擇器用於選擇特定元素的緊鄰下一個兄弟元素。

為了更好地理解這一點,讓我們考慮以下兩個示例場景:

場景 1:在 <div> 元素之後緊跟著兩個 <p> 元素。

$("div + p"):  This will only select the first <p> element, because it only selects one element (the other <p> element will be ignored). 

場景 2:如果您有一個 <div> 元素,緊跟著一個 <h2> 元素,然後是一個 <p> 元素。

$("div + p"):  This will not select the <p> element, because the immediate element of <div> is <h2>, not <p>. 
此選擇器僅選擇緊鄰的下一個兄弟元素。如果您需要選擇多個兄弟元素或非緊鄰的元素,請考慮使用其他遍歷方法,例如next()nextAll()nextUntil()

語法

以下是 jQuery 元素 + next 選擇器的語法:

("element + next")

引數

以下是上述語法的描述:

  • 元素:任何有效的 jQuery 選擇器。
  • next:指定應為 `element` 引數的緊鄰元素的元素。

示例 1

在此示例中,我們使用 jQuery 元素 + next 選擇器來選擇緊鄰 <div> 元素的 <p> 元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("div + p").css("background-color", "yellow");
      });
    </script>
</head>
<body>
    <div style="border: 2px solid black;">Div element.</p></div>
    <p>Paragraph element.</span>
    <p>This is another paragraph.</p>
</body>
</html>

執行上述程式後,我們可以看到緊鄰的 <p> 元素被選中並突出顯示。

示例 2

在此示例中,我們選擇緊鄰 <div> 元素的 <p> 元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("div + p").css("background-color", "yellow");
      });
    </script>
</head>
<body>
    <div style="border: 2px solid black;">Div element.</p></div>
    <h2>Heading element.</h2>
    <p>Paragraph element.</p>
</body>
</html>

上述程式將不會選擇 <p> 元素,因為 <div> 元素的下一個元素是 <h2>。

jquery_ref_selectors.htm
廣告