在 jQuery 中,如果想要替换元素,我们用 replaceWith() 方法和 replaceAll() 方法来实现。下面进行分别介绍。
在 jQuery 中,我们可以使用 replaceWith() 方法来将所选元素替换成其他元素。
语法:
$(A).replaceWith(B) 表示用 B 来替换 A。
举例:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <script src="js/jquery-1.12.4.min.js"></script>
- <script>
- $(function () {
- $("#btn").click(function () {
- $("strong").replaceWith('<a href="http://www.cdsy.xyz/" target="_blank">城东书院</a>');
- });
- })
- </script>
- </head>
- <body>
- <strong>jQuery教程</strong><br/>
- <input id="btn" type="button" value="替换" />
- </body>
- </html>
默认情况下,预览效果如图 1 所示。
我们点击【替换】按钮后,此时预览效果如图 2 所示。
在 jQuery 中,replaceAll() 和 replaceWith() 这两个方法功能虽然相似,都是将某个元素替换成其他元素,但是两者的操作对象是颠倒的。
语法
$(A).replaceAll(B) 表示用 A 来替换 B。对于 replaceAll() 和 replaceWith() 这两个方法,我们可以根据英文意思来帮助理解和记忆。
举例:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <script src="js/jquery-1.12.4.min.js"></script>
- <script>
- $(function () {
- $("#btn").click(function () {
- $('<a href="http://www.cdsy.xyz/" target="_blank">城东书院</a>').replaceAll("strong");
- });
- })
- </script>
- </head>
- <body>
- <strong>jQuery教程</strong><br/>
- <input id="btn" type="button" value="替换" />
- </body>
- </html>
默认情况下,预览效果如图 3 所示。
我们点击【替换】按钮后,此时预览效果如图 4 所示。
在下面的代码中,这两种插入节点的方式是等价的。
- //方式1
- $("strong").replaceWith('<a href="http://www.cdsy.xyz/" target="_blank">城东书院</a>');
- //方式2
- $('<a href="http://www.cdsy.xyz/" target="_blank">城东书院</a>').replaceAll("strong");
此外,对于 replaceAll() 和 replaceWith() 这两个方法,我们只需要掌握其中一种即可。