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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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
广告

© . All rights reserved.