当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JQuery wrap()用法及代码示例


wrap()方法是jQuery中的内置方法,用于将指定元素包装在选定元素周围。

用法:

$(selector).wrap(element, function)

参数:此方法接受上述和以下所述的两个参数:


  • element:这是必需的参数,用于指定要包裹所选元素的元素。
  • function:它是可选参数,用于指定返回包装元素的函数。

返回值:此方法返回通过wrap()方法进行指定更改的所选元素。

以下示例说明了jQuery中的wrap()方法:

示例1:本示例不接受可选参数。

<!DOCTYPE html> 
<html> 
    <head> 
        <title>The wrap() Method</title> 
        <script src= 
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
          
        <!-- jQuery code to show the working of this method -->
        <script> 
            $(document).ready(function() { 
                $("button").click(function() { 
                    $("p").wrap("<div></div>"); 
                }); 
            }); 
        </script> 
        <style> 
            div { 
                background-color: lightgreen; 
                padding: 20px; 
                width: 200px; 
                font-weight: bold; 
                height: 60px; 
                border: 2px solid green; 
            } 
        </style> 
    </head> 
       
    <body> 
        <!-- click on this paragraph and see the change -->
        <p>Welcome to GeeksforGeeks!</p><br> 
        <button>Click Here!</button> 
    </body> 
</html>

输出:
wrap method

示例2:

<!DOCTYPE html> 
<html> 
    <head> 
        <title>The wrap Method</title> 
        <script src= 
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
          
        <!-- jQuery code to show the working of this method -->
        <script> 
            $(document).ready(function() { 
                $("button").click(function() { 
                    $("p").wrap(function() { 
                        return "<div></div>" 
                    }); 
                }); 
            }); 
        </script> 
        <style> 
            div { 
                background-color: lightgreen; 
                padding: 20px; 
                width: 200px; 
                font-weight: bold; 
                height: 60px; 
                border: 2px solid green; 
            } 
        </style> 
    </head> 
    <body> 
        <!-- click on this paragraph and see the change -->
        <p>Welcome to GeeksforGeeks!</p><br> 
        <button>Click Here!</button> 
    </body> 
</html>

输出:
wrap method



相关用法


注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 jQuery | wrap() with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。