jQuery wrap() 方法



jQuery 中的 wrap() 方法用於在選定元素集中的每個元素周圍包裝一個 HTML 結構。

注意:如果您想將 HTML 結構包裝在所有匹配的元素周圍作為一個整體,wrapAll() 是更合適的方法。

語法

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

$(selector).wrap(wrappingElement,function(index))

引數

此方法接受以下引數:

  • wrappingElement: 指定要圍繞每個選定元素包裝的 HTML 元素。可能的值包括:HTML 元素、DOM 元素、jQuery 物件。
  • function (index): (可選)為每個選定元素執行的函式。

示例 1

使用 wrap() 方法與 HTML 元素

在下面的示例中,我們使用 wrap() 方法將每個 <p> 元素包裝在一個 <div> 元素中:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $('p').wrap('<div></div>').css({"border": "2px solid green"});
      });
    });
  </script>
</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> 元素並以綠色實線邊框突出顯示。

示例 2

使用 wrap() 方法與 DOM 元素

這與第一個示例類似,它將每個 <p> 元素包裝在一個 <div> 元素中:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $('p').wrap(document.createElement('div')).css({"border": "2px solid green"});
      });
    });
  </script>
</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').wrap($('<div></div>')).css({"border": "2px solid green"});
        });
      });
  </script>
</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> 元素並以綠色實線邊框突出顯示。

示例 4

使用 wrap() 方法與 回撥 函式

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

因此,當點選按鈕時,每個 <p> 元素都用 <div> 元素包裝,並且包裝的元素將以綠色邊框突出顯示。

jquery_ref_html.htm
廣告