替换节点 replaceWith 与 replaceAll的区别

---恢复内容开始---

首先我主要从两方面来说:

1、大的方面 

2、小的方面

直接用代码来实践:

从大的方面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>替換節點</title>
    <script type="text/javascript" src="../jquery-3.4.1.min.js"></script>
</head>
<body>

<div class="replace">
    <p id="a">一欸及</p>
    <p id="b">三体人</p>
</div>

<!--script要写在后面-->
<script>

    /*
    兩種方法 1.replaceWith   2.replaceAll
     */

    //需求: 将div下面的p标签换成span标签

    //1、使用replaceWith(第一种方法)
    //语法 $(old).replaceWith(new);
    $("#a").replaceWith("<span>你好</span>");


    //2、使用replaceAll
    //语法:   $(new).replaceAll(old);
    $("<span>世界</span>").replaceAll("#b");


</script>


</body>
</html>

总结:     用法上不同 ,replaceWith是先旧的,后面写新的     replaceAll是先新的,后面才写旧的

$(old).replaceWith(new);
$(new).replaceAll(old);

 

都能得到想要的结果(前提:     使用replaceAll方法中new里填的都是非字符串)

 

从小的方面来说:

 

原来页面结果

 

 

 

使用replaceWith和replaceAll两者都在new中填的是非字符串

 

 

结果为   :   (这里没有像上面一样一个占一行  是因为上面使用p标签隔开了 ,但这里没隔开没关系 不妨碍测试)

 

 

 

 很明显的看到 : 成功实现了效果

使用replaceWith和replaceAll两者都在new中填的是字符串

 

 

测试结果:

 

 很明显看到第一个replaceWith方法可以使用字符串达到效果,但replaceAll方法使用字符串却没报错但也没显示

这里明显就是一个BUG 也就是replaceAll方法有一个坑 里面写字符串通常是没效果的

 

---恢复内容结束---

首先我主要从两方面来说:

1、大的方面 

2、小的方面

直接用代码来实践:

从大的方面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>替換節點</title>
    <script type="text/javascript" src="../jquery-3.4.1.min.js"></script>
</head>
<body>

<div class="replace">
    <p id="a">一欸及</p>
    <p id="b">三体人</p>
</div>

<!--script要写在后面-->
<script>

    /*
    兩種方法 1.replaceWith   2.replaceAll
     */

    //需求: 将div下面的p标签换成span标签

    //1、使用replaceWith(第一种方法)
    //语法 $(old).replaceWith(new);
    $("#a").replaceWith("<span>你好</span>");


    //2、使用replaceAll
    //语法:   $(new).replaceAll(old);
    $("<span>世界</span>").replaceAll("#b");


</script>


</body>
</html>

总结:     用法上不同 ,replaceWith是先旧的,后面写新的     replaceAll是先新的,后面才写旧的

$(old).replaceWith(new);
$(new).replaceAll(old);

 

都能得到想要的结果(前提:     使用replaceAll方法中new里填的都是非字符串)

 

小的方面来说:

replaceAll方法中

如果new里面填的是字符串的话那么

原来页面结果

 

 

 

使用replaceWith和replaceAll两者都在new中填的是非字符串

 

 

结果为   :   (这里没有像上面一样一个占一行  是因为上面使用p标签隔开了 ,但这里没隔开没关系 不妨碍测试)

 

 

 

 很明显的看到 : 成功实现了效果

使用replaceWith和replaceAll两者都在new中填的是字符串

 

 

测试结果:

 

 很明显看到第一个replaceWith方法可以使用字符串达到效果,但replaceAll方法使用字符串却没报错但也没显示

这里明显就是一个BUG 也就是replaceAll方法有一个坑 里面写字符串通常是没效果的

 

 

 

 

最后总结:    通常情况下  ,如果 new里填非字符串

replaceWith 和 replaceAll 两者都能实现效果

但如果 new里填的是字符串

那replaceWith可以实现 ,但replaceAll 可能不能实现效果

 

posted @ 2019-09-13 10:42  AxeBurner  阅读(995)  评论(0编辑  收藏  举报