jQuery中remove方法和detach方法的区别

remove() 和 detach()都是删除元素的方法 那他们的区别是??
remove方法:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        #div1{
            width: 100px;
            height: 100px;
            background-color: red;
        }
        #div2{
            width: 200px;
            height: 200px;
            border: 1px solid black;
        }
    </style>
    <script src="./jquery/jquery.js"></script>
    <script>
        $(function (){
            $("button").click(function(){
                //remove的返回值就是删除的这个节点
                //$("#div1").remove();
                var node=$("#div1").remove();//把div1删除
                node.appendTo($("#div2"));//把删除的div1添加到div2里
            })
        })

    </script>
</head>
<body>
<button>删除节点</button>
<div id="div1" title="hello" class="box"></div>
<div id="div2"></div>
</body>
</html>

在这里插入图片描述

在删除div1之前给div1添加一个鼠标移入移出事件:

<script>
    $(function (){
        $("#div1").hover(function(){
            $(this).css("backgroundColor","orange");
        },function(){
            $(this).css("background","blue");
    });
        $("button").click(function(){
            //remove的返回值就是删除的这个节点
            //$("#div1").remove();
            var node=$("#div1").remove();//把div1删除
            node.appendTo($("#div2"));//把删除的div1添加到div2里
        })
    })

</script>

当没删除div1 之前移入移出的事件都可以执行 但当删除div1 之后再移入移出这些事件都不在了
所以 remove()不会保留这个元素节点上之前的事件和行为

datach方法
<script>
    $(function (){
        $("#div1").hover(function(){
            $(this).css("backgroundColor","orange");
        },function(){
            $(this).css("background","blue");
    });
        $("button").click(function(){
            //$("#div1").detach();
            var node=$("#div1").detach();//把div1删除
            node.appendTo($("#div2"));//把删除的div1添加到div2里
        })
    })

</script>

detach()保留这个元素节点上之前的事件和行为

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值