jQuery DOM oper...LOGIN

jQuery DOM operation detach()

If we want to temporarily delete a node on the page, but do not want the data and events on the node to be lost, and can have the deleted node displayed on the page in the next time period, then we can use the detach method to handle it

detach is easy to understand literally. Let a web element be hosted. That is, the element is removed from the current page, but the memory model object of this element is retained.

Let’s take a look at the explanation from jquery official documentation:

This method will not delete the matching elements from the jQuery object, so these matching elements can be used again in the future. Unlike remove(), all bound events, attached data, etc. will be retained.
$("div").detach() will remove the object, but the display effect will be gone. But it still exists in memory. When you append, you return to the document flow. It showed up again.

Of course, special attention should be paid here. The detach method is unique to JQuery, so it can only process events or data bound through JQuery methods.

Refer to the code area on the right, through $("p").detach() deletes all P elements, and then puts the deleted p elements on the page through append. By clicking on the text, you can prove that the event is not lost.

Let’s take a look below Example code:

<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    <style type="text/css">
    p {
        color: red;
    }
    </style>
</head>

<body>
    <p>P元素1,默认给绑定一个点击事件</p>
    <p>P元素2,默认给绑定一个点击事件</p>
    <button id="bt1">点击删除 p 元素</button>
    <button id="bt2">点击移动 p 元素</button>
    <script type="text/javascript">
    $('p').click(function(e) {
        alert(e.target.innerHTML)
    })
    var p;
    $("#bt1").click(function() {
        if (!$("p").length) return; //去重
        //通过detach方法删除元素
        //只是页面不可见,但是这个节点还是保存在内存中
        //数据与事件都不会丢失
        p = $("p").detach()
    });

    $("#bt2").click(function() {
        //把p元素在添加到页面中
        //事件还是存在
        $("body").append(p);
    });
    </script>
</body>

</html>


Next Section
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style type="text/css"> p { color: red; } </style> </head> <body> <p>P元素1,默认给绑定一个点击事件</p> <p>P元素2,默认给绑定一个点击事件</p> <button id="bt1">点击删除 p 元素</button> <button id="bt2">点击移动 p 元素</button> <script type="text/javascript"> $('p').click(function(e) { alert(e.target.innerHTML) }) var p; $("#bt1").click(function() { if (!$("p").length) return; //去重 //通过detach方法删除元素 //只是页面不可见,但是这个节点还是保存在内存中 //数据与事件都不会丢失 p = $("p").detach() }); $("#bt2").click(function() { //把p元素在添加到页面中 //事件还是存在 $("body").append(p); }); </script> </body> </html>
submitReset Code
ChapterCourseware