先看一段代码,这里函数处理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');
。。。。。
}
};
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
比较一下jquery删除内容的方法
1、empty()
源码
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( 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;
},
3、detach()
与remove empty不同可以保存 数据和事件 ,同样可用
源码 调用了remove
detach: function( selector ) {
return this.remove( selector, true );
},
看 官方demo
元素的样式也会被保留
找找detach()源码。。。。。。。。。
<html lang="en">
<head>
<meta charset="utf-8">
<title>detach demotitle>
<style>
p {
background: yellow;
margin:6px 0;
}
p.off{
background: black;
}
style>
<script src="//code.jquery.com/jquery-1.10.2.js">script>
head>
<body>
<p>Hellop>
how are
<p>you?p>
<button>Attach/detach paragraphsbutton>
<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>