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


JQuery replaceWith()用法及代码示例


replaceWith()方法是jQuery中的内置方法,用于将所选元素替换为新元素。

用法:

$(selector).replaceWith(content, function)

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


  • content:这是必需的参数,用于指定需要替换的内容。
  • para2:它是一个可选参数,在调用后执行。

返回值:此方法返回具有更改的所选元素。

以下代码说明了jQuery中的replaceWith()方法:

示例1:

<!DOCTYPE html> 
<html> 
    <head> 
        <title>The replaceWith method</title> 
        <script src= 
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
        <style> 
            button { 
                display: block; 
                margin: 10px; 
                color: red; 
                width: 200px; 
                padding: 3px; 
            } 
            div { 
                color: green; 
                border: 2px solid green; 
                width: 200px; 
                margin: 3px; 
                padding: 5px; 
                font-size: 20px; 
                text-align: center; 
            } 
        </style> 
    </head> 
    <body> 
        <!-- click on individual button and see the change -->
        <button>Geeks</button> 
        <button>for</button> 
        <button>Geeks</button> 
          
        <!-- jQuery code to show the working of this method -->
        <script> 
            $("button").click(function() { 
                $(this).replaceWith("<div>" + $(this).text() + "</div>"); 
            }); 
        </script> 
    </body> 
</html>

输出:
在单击任何按钮之前:

单击所有按钮后:

示例2:在下面的代码中,传递了可选函数。

<!DOCTYPE html> 
<html> 
    <head> 
        <title>The replaceWith method</title> 
        <script src= 
        "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
        <style> 
            button { 
                display: block; 
                margin: 4px; 
                color: green; 
                width: 150px; 
                padding: 5px; 
            } 
            div { 
                width: 200px; 
                height: 100px; 
                padding: 20px; 
                border: 2px solid green; 
            } 
        </style> 
    </head> 
    <body> 
        <div> 
            <p>Welcome to </p> 
              
            <!-- click on this button and see the change -->
            <button>Click Here!</button> 
        </div> 
          
        <!-- jQuery code to show the working of this method -->
        <script> 
            var x = "GeeksforGeeks!"; 
            $("button").click(function() { 
                $("p").replaceWith(x).replaceWith(function(n) { 
                    alert("Click ok and string will replace"); 
                    return n; 
                }); 
            }); 
        </script> 
    </body> 
</html>

输出:
replacewith



相关用法


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