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


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() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。