replaceWith()方法是jQuery中的一个内置方法,用于将所选元素替换为新元素。
null
语法:
$(selector).replaceWith(content, function)
参数: 该方法接受两个参数,如下所述:
- 内容: 它是必需的参数,用于指定需要替换的内容。
- para2: 它是一个可选参数,在调用后执行。
返回值: 此方法返回带有更改的选定元素。
下面的代码演示了jQuery中的replaceWith()方法:
例1:
<!DOCTYPE html> < html > < head > < title >The replaceWith method</ title > < script src = </ 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 = </ 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 > |
输出:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END