.remove()
.remove( [ selector ] ) 返回:jQuery
描述:將匹配元素從DOM中刪除。
-
version added: 1.0.remove( [ selector ] )
selector一個(gè)選擇表達(dá)死用來(lái)過(guò)濾匹配的將被移除的元素。
和 .empty()相似。.remove() 將元素移出DOM。
當(dāng)我們想將元素自身移除時(shí)我們用 .remove(),同時(shí)也會(huì)移除元素內(nèi)部的一切,包括綁定的事件及與該元素相關(guān)的jQuery數(shù)據(jù)。
請(qǐng)看下面的HTML:
<div class="container"> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div>
我們可以移除里面的任何目標(biāo)元素:
$('.hello').remove();
結(jié)果如下:
<div class="container"> <div class="goodbye">Goodbye</div> </div>
如果<div class="hello">元素里面有子元素,他們同樣會(huì)被移除。于它相關(guān)的事件句柄也將被擦除。
我們也可以添加一個(gè)可選參數(shù)來(lái)過(guò)濾匹配的元素。例如,前面的代碼可以重寫為:
$('div').remove('.hello');
結(jié)果將一樣:
<div class="container"> <div class="goodbye">Goodbye</div> </div>
Examples:
Example: 將所有段落從DOM刪除:
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; margin:6px 0; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
<script>
$("button").click(function () {
$("p").remove();
});
</script>
</body>
</html>
Demo:
Example: 將所有包含"Hello"的段落從DOM中刪除。
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; margin:6px 0; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p class="hello">Hello</p>
how are
<p>you?</p>
<button>Call remove(":contains('Hello')") on paragraphs</button>
<script>
$("button").click(function () {
$("p").remove(":contains('Hello')");
});
</script>
</body>
</html>