DOM节点删除之remove()的有参用法和无参用法
remove与empty一样,都是移除元素的方法,但是remove会将元素自身移除,同时也会移除元素内部的一切,包括绑定的事件及与该元素相关的jQuery数据。
例如一段节点,绑定点击事件
<div class="hello"><p>慕课网</p></div>
$('.hello').on("click",fn)
如果不通过remove方法删除这个节点其实也很简单,但是同时需要把事件给销毁掉,这里是为了防止"内存泄漏",所以前端开发者一定要注意,绑了多少事件,不用的时候一定要记得销毁
通过remove方法移除div及其内部所有元素,remove内部会自动操作事件销毁方法,所以使用使用起来非常简单
//通过remove处理
$('.hello').remove()
//结果:<div class="hello"><p>慕课网</p></div> 全部被移除
//节点不存在了,同事事件也会被销毁 也就是class=.hello这个类名也会被删除
remove表达式参数:
remove比empty好用的地方就是可以传递一个选择器表达式用来过滤将被移除的匹配元素集合,可以选择性的删除指定的节点
$("p").filter(":contains('3')").remove()//选择性的销毁数据
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
<style>
.test1 {
background: #bbffaa;
}
.test2 {
background: yellow;
}
</style>
</head>
<body>
<h2>通过jQuery remove方法移除元素</h2>
<div class="test1">
<p>p元素1</p>
<p>p元素2</p>
</div>
<div class="test2">
<p>p元素3</p>
<p>p元素4</p>
</div>
<button>通过点击jQuery的empty移除元素</button>
<button>通过点击jQuery的empty移除指定元素</button>
<script type="text/javascript">
$("button:first").on('click', function() {
//删除整个 class="test1"的div节点
$(".test1").remove()
})
$("button:last").on('click', function() {
//找到所有p元素中,包含了3的元素
//这个也是一个过滤器的处理
$("p").remove(":contains('4')")
})
</script>
</body>
</html>
孜孜不倦,必能求索;风尘仆仆,终有归途。

浙公网安备 33010602011771号