當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。