jquery中使用detach 移除元素的使用场合

detach()函数用于从文档中移除匹配的元素,与remove()相比,detach()函数不会移除与元素关联绑定的附加数据( data()函数 )和事件等(remove()会移除)。

如果要删除以后不再利用的元素时,使用empty或者remove。


一、detach()的使用场合

当我们要对一个元素进行大规模的增删改的时候,我们可以用detach将这个元素提取出来,然后在这个元素上进行操作,而不是在整个dom文档中进行操作。

好处就是:减少对整个dom文档的修改,从而减少页面重绘;

 

二、实例

首先对#container元素绑定click事件,然后利用detach将其脱离文档,然后再创建两个child元素,追加到#container元素中,最后将#container重新添加到body

			
<!DOCTYPE html> 
    <head>
        <title>jQuery</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style>
            div.monkey, #container {}{
                width:120px;
                height:120px;
                line-height:60px;
            }
            div.monkey {}{
                border:1px solid black;
            }            
        </style>
    </head>
    <body>
        <div class="monkey"> </div>
        <div id="container"> </div>
        <script src="jquery-1.12.0.js"></script>
        <script>
            $(function(){
                //事件代理
                $('#container').on('click',function( event ){
                    console.log( $(event.target).text() );
                });
                //利用detach将container从dom文档中剥离开
                var container = $('#container').detach();
                var child1 = '<div>I am Monkey</div>';
                var child2 = '<div>Monkey is me</div>';
                //将child1、child2插入container中
                $(container).append( child1 )
                            .append( child2 );
                //将container重新插入body中            
                $('body').append( container );
            });    
        </script>
    </body>
</html>

		

文章转载自:jquery中使用detach 移除元素的使用场合  http://www.studyofnet.com/news/1225.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章