Jquery 删除元素remove() detach() empty()比较

来源:互联网 发布:期货 期权 知乎 编辑:程序博客网 时间:2024/06/04 17:50

先看一段代码,这里函数处理ajax请求的返回结果,将表格的内容先移除然后重新添加

function dispose(data){var data = eval('('+ data +')');var dataJson = data.Json;if(data.state == 'success'){$('#bugboardTable tbody').empty().prepend(bugBoardData.bugBoardData(dataJson).str);var length = bugBoardData.bugBoardData(dataJson).i;$('.pageNum em').html('共'+ length +'条');poolVamp('#container');。。。。。}};

这么做导致的问题是 table中有一列绑定了事件 但是remove后不只是旧的数据 连绑定的事件也会被清除,所以只能重新绑定

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

比较一下jquery删除内容的方法

1、empty()

源码

empty: function() {var elem,i = 0;for ( ; (elem = this[i]) != null; i++ ) {// Remove element nodes and prevent memory leaksif ( elem.nodeType === 1 ) {jQuery.cleanData( getAll( elem, false ) );}// Remove any remaining nodeswhile ( elem.firstChild ) {elem.removeChild( elem.firstChild );}// If this is a select, ensure that it displays empty (#12336)// Support: IE<9if ( elem.options && jQuery.nodeName( elem, "select" ) ) {elem.options.length = 0;}}return this;},


清除这个标签内的所有内容,为了防止内存泄漏并且会清空数据和事件

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

(关于jquery内存泄漏----> jquery数据缓存的介绍)

2、remove()

在empty删除内容上 连元素本身也会删除 包括data和event

remove是可带参数的 remove([selector]) 可以添加一个选择器

例如:从dom删除包含“p1”字符的 p 元素

$(document).ready(function(){  $("button").click(function(){    $("p").remove(":contains('p1')");/*remove() empty()*/  });

这是1.62的remove源码

remove: function( selector, keepData /* Internal Use Only */ ) {var elem,elems = selector ? jQuery.filter( selector, this ) : this,i = 0;for ( ; (elem = elems[i]) != null; i++ ) {if ( !keepData && elem.nodeType === 1 ) {jQuery.cleanData( getAll( elem ) );}if ( elem.parentNode ) {if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {setGlobalEval( getAll( elem, "script" ) );}elem.parentNode.removeChild( elem );}}return this;},

看setGlobalEval名字应该 是将内容存为全局变量

3、detach()

与remove empty不同可以保存 数据和事件 ,同样可用 

源码 调用了remove

detach: function( selector ) {return this.remove( selector, true );},



看 官方demo

元素的样式也会被保留

找找detach()源码。。。。。。。。。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>detach demo</title>
<style>
p {
background: yellow;
margin:6px0;
}
p.off{
background: black;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Attach/detach paragraphs</button>
<script>
$( "p" ).click(function() {
$( this ).toggleClass( "off" );
});
var p;
$( "button" ).click(function() {
if ( p ) {
p.appendTo( "body" );
p = null;
} else {
p = $( "p" ).detach();
}
});
</script>
</body>
</html>















0 0
原创粉丝点击