jQuery wrapAll() 方法



jQuery 中的wrapAll() 方法用於在一個選定的 HTML 結構中包裹所有被選擇器匹配的元素。它將指定的 HTML 結構作為一個單元包裹在所有匹配元素的周圍。

注意:如果你想在選定元素集中的每個元素周圍包裹一個 HTML 結構,則應使用wrap() 方法。

語法

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

$(selector).wrapAll(wrappingElement)

引數

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

  • wrappingElement: 指定要圍繞每個選定元素包裹的 HTML 元素。可能的值包括:HTML 元素、DOM 元素、jQuery 物件。

示例 1

使用 wrap() 方法和HTML 元素

在下面的例子中,我們使用 wrapAll() 方法在一個單一的 HTML 結構 (<div>) 中包裹所有 <p> 元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("p").wrapAll("<div></div>");
      });
    });
  </script>
  <style>
    div{
      border: 2px solid green;
    }
  </style>
</head>
<body>
  <p>Paragraph element.</p>
  <p>This is another Paragraph element.</p>
  <button>Click me!</button>
</body>
</html>

點選按鈕後,<div> 元素將作為一個單元包裹所有 <p> 元素,並用綠色實線邊框突出顯示。

示例 2

使用 wrap() 方法和DOM 元素

這與第一個例子類似,它使用 <div> 元素包裹所有 <p> 元素:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $('p').wrapAll(document.createElement('div'));
      });
    });
  </script>
  <style>
    div{
      border: 2px solid green;
    }
  </style>
</head>
<body>
    <p>Paragraph element.</p>
    <p>This is another Paragraph element.</p>
	  <h3>Heading element.<h3>
    <button>Click me!</button>
</body>
</html>

點選按鈕後,<div> 元素將包裹所有 <p> 元素,並用綠色實線邊框突出顯示。

示例 3

使用 wrap() 方法和jQuery 物件

這裡,我們使用 <div> 元素包裹所有 <p> 元素:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $('p').wrapAll($('<div></div>'));
        });
      });
  </script>
  <style>
    div{
      border: 2px solid green;
    }
  </style>
</head>
<body>
    <p>Paragraph element.</p>
    <p>This is another Paragraph element.</p>
	  <h3>Heading element.<h3>
    <button>Click me!</button>
</body>
</html>

點選按鈕後,<div> 元素將包裹所有 <p> 元素,並用綠色實線邊框突出顯示。

jquery_ref_html.htm
廣告
© . All rights reserved.