替换元素节点

在jQuery中,如果要替换元素中的节点,可以使用 replaceWith() replaceAll() 这两种方法,其语法格式分别如下:

replaceWith(content):该方法的功能是将所有选择的元素替换成指定的HTML或DOM元素,其中参数content为被所选择元素替换的内容。

replaceAll(selector):该方法的功能是将所有选择的元素替换成指定selector的元素,其中参数selector为需要被替换的元素。

replaceWith()与replaceAll()方法都可以实现元素节点的替换,二者最大的区别在于替换字符的顺序,前者是用括号中的字符替换所选择的元素。后者是用字符串替换括号中所选择的元素。同时,一旦完成替换,被替换元素中的全部事件都将消失。

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 5 <title>jq替换元素节点</title>
 6 <style>
 7     body{font-size: 12px;}
 8     span{font-weight: bold;}
 9     p{background-color: #eee;padding: 5px;width: 200px;}
10 </style>
11 <script type="text/javascript" src="jquery-1.8.3.js"></script>
12 <script>
13     $(function(){
14         $("#Span1").replaceWith("<span title='replaceWith'>白小虫</span>");
15         $("<span title='replaceAll'>1176118119@qq.com</span>").replaceAll("#Span2");
16     });
17     alert(1);
18 </script>
19 </head>
20 <body>
21     <p>姓名:<span id="Span1"></span></p>
22     <p>邮箱:<span id="Span2"></span></p>
23 </body>
24 </html>

结果如下图所示:

高否?富否?帅否? 否? 滚去学习!
原文地址:https://www.cnblogs.com/baixc/p/3387506.html