单击按钮后,div元素
id ="d1" 的标题替换为
h1 ,而
id ="d2" 的div元素替换为标题< strong> h2 。
id ="p1" 的段落元素的文本被替换为新内容,而
id ="btn" 的按钮被替换为带有< strong> id ="d3" 。
<!DOCTYPE html> <html> <head> <title> jQuery replaceWith() method </title> <script src= "/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <style> div { border: 2px dashed blue; width: auto; margin: 8px; font-size: 23px; text-align: center; } h1, h2{ background-color: yellow; color: blue; } #d3{ border: 2px solid blue; width: 150px; height: 15px; } </style> </head> <body> <p> This is an example of using the jQuery replaceWith() method. </p> <div id = "d1"> This is a div element </div> <div id = "d2"> This is another div element. </div> <p id = "p1"> Click the following button to see the effect </p> <button id = "btn"> Click me </button> <script> $(document).ready(function(){ $("button").click(function() { $("#d1").replaceWith("<h1> Hello world :) </h1>"); $("#d2").replaceWith("<h2> Welcome to the lidihuo.com </h2>"); $("#p1").replaceWith("<p> This is a paragraph element </p>"); $("#btn").replaceWith("<div id = 'd3'> </div>"); }); }); </script> </body> </html>
输出:
This is an example of using the jQuery replaceWith() method.
<!DOCTYPE html> <html> <head> <title> jQuery replaceWith() method </title> <script src= "/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <style> div { border: 2px dashed blue; width: auto; margin: 8px; text-align: center; } h3{ background-color: yellow; color: blue; } </style> </head> <body> <p> This is an example of using the jQuery replaceWith() method. </p> <div> This is a div element </div> <p class = "para"> This is a paragraph element </p> <div> This is another div element </div> <p class = "para"> This is another paragraph element </p> <p class = "para"> Click the following button to see the effect </p> <button id = "btn"> Click me </button> <script> $(document).ready(function(){ $("button").click(function(){ $(".para").replaceWith(function(index){ return "<h4> This is a paragraph element with index: " + index + ".</h4>"; }); $("div").replaceWith(function(index){ return "<h3> This is a div element with index: " + index + ".</h3>"; }); }); }); </script> </body> </html>