Spiner_0
2018-03-15 17:20
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
    <style>
    .right div {
        background: yellow;
    }
    </style>
</head>
<body>
    <h2>replaceWith()和replaceAll()</h2>
    <div class="left">
        <button class="bt1">点击,通过replaceWith替换内容</button>
        <button class="bt2">点击,通过rreplaceAll替换内容</button>
    </div>
    <div class="right">
        <div>
            <p>第一段</p>
            <p>第二段</p>
            <p>第三段</p>
        </div>
        <div>
            <p>第四段</p>
            <p>第五段</p>
            <p>第六段</p>
        </div>
    </div>
    <script type="text/javascript">
    //只克隆节点
    //不克隆事件
    $(".bt1").on('click', function() {
        //找到内容为第二段的p元素
        //通过replaceWith删除并替换这个节点
        $(".right > div:first p:eq(1)").replaceWith('<a style="color:red">replaceWith替换第二段的内容</a>')
      
    })
    </script>
    <script type="text/javascript">
    //找到内容为第六段的p元素
    //通过replaceAll删除并替换这个节点
    $(".bt2").on('click', function() {
        $('<a style="color:red">replaceAll替换第六段的内容</a>').replaceAll('.right > div:last p:last');
    })
    </script>
</body>
</html>
				<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
    <style>
        .right div {
            background: yellow;
        }
    </style>
</head>
<body>
<h2>replaceWith()和replaceAll()</h2>
<div class="left">
    <button class="bt1">点击,通过replaceWith替换内容</button>
</div>
<div class="right">
    <div>
        <p>第一段</p>
        <p>第二段</p>
        <p>第三段</p>
    </div>
    <div>
        <p>第四段</p>
        <p>第五段</p>
        <p>第六段</p>
    </div>
</div>
<script type="text/javascript">
    //只克隆节点
    //不克隆事件
    $(".bt1").on('click', function() {
        //找到内容为第二段的p元素
        //通过replaceWith删除并替换这个节点
        $(".right div:first p:eq(1)").replaceWith('<p  style="color:red">replaceWith替换第二段的内容</p>')
    })
</script>
</body>
</html>
同学, $(".right > div:first p:eq(1)").replaceWith('<a style="color:red">replaceWith替换第二段的内容</a>')
你把p元素替换成啦a元素,那么第一个div里面只有2个p元素啦,之前第3个p元素那就变成第二p元素,所以当你连续点击2次时,<p>第二段</p>和<p>第三段</p>都被替换掉。
<div>
      <p>第一段</p>
       <a>第二段</a>
       <p>第三段</p>
   </div>
jQuery基础(二)—DOM篇
113996 学习 · 614 问题
相似问题