您的位置:首页 > Web前端 > JQuery

jquery中detach()移除元素

2016-04-20 00:00 423 查看
一、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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery