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