jQuery--删除节点(remove()、detach()、empty())详解

删除节点

在jQuery中提供了remove()和detach()方法,用于删除元素节点;empty()方法用于清空当前元素中的内容,而元素的标签部分仍被保留。

1. remove()方法:
remove()方法用于删除所匹配的元素,包括该元素的文本节点和子节点。该方法返回一个jQuery对象或数组,其中包含被删除元素的基本内容,但不包含所绑定的事件和附加数据等信息。remove()方法的语法格式如下:

var jQueryObject = $(selector).remove();
//$(selector)表示需要被删除的元素

2. detach()方法:
detach()方法用于删除所匹配的元素,包括该元素的文本节点和子节点。该方法将返回一个jQuery对象或数组,其中包含被删除元素的基本内容、绑定事件以及附加数据等信息。detach()方法的语法格式如下:

var jQueryObject = $(selector).detach();
//$(selector)表示需要被删除的元素

3. empty()方法:
empty()方法用于清空元素的内容(包括所有文本和子节点),但不删除该元素,其语法格式如下:

$(selector).empty()
//$(selector)表示要被清空的元素

示例:

<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>删除节点-jQuery</title>
	<script type="text/javascript" src="js/jquery-1.x.js">
	</script>
	<style type="text/css">
		img{height:250px;width:240px;}
		table{border:0px; text-align:center;}
		table td{width:240px;}
	</style>
</head>
<body>
	<table  border="1">
      <tr>
        <td id="firstCell"><img src="images/clothe1.jpg" /></td>
        <td id="secondCell"><img src="images/clothe2.jpg" /></td>
        <td id="thirdCell"><img src="images/clothe3.jpg" /></td>
      </tr>
      <tr>
        <td>
        	<input type="button" value="remove" id="removeBtn"/>
            <input type="button" value="recovery" id="recoveryRemoveBtn"/>
        </td>
        <td>
        	<input type="button" value="detach" id="detachBtn"/>
            <input type="button" value="recovery" id="recoveryDetachBtn"/>
        </td>
        <td>
        	<input type="button" value="empty" id="emptyBtn"/>
        </td>
      </tr>
    </table>
	<script type="text/javascript">
	$(function (e) {
		var firstImage;
		var secondImage;
		//为每幅图像附加数据
		$("img:first").data("msg", "皮草大卖场-漫步时尚广场");
		$("img:eq(1)").data("msg", "电子产品专卖-漫步时尚广场");
		$("img:last").data("msg", "西装个人定制-漫步时尚广场");
		//为图像绑定click事件
		$("img").click(function(){
			alert($(this).data("msg"));
		});
		//removeBtn按钮绑定click事件
		$("#removeBtn").click(function(){
			if(($("#firstCell img").length)>0){
				firstImage=$("#firstCell img").remove();
			}
		});
		//恢复removeBtn按钮删除的图像
		$("#recoveryRemoveBtn").click(function(){
			$("#firstCell").append(firstImage);
		});
		//detachBtn按钮绑定click事件
		$("#detachBtn").click(function(){
			if(($("#secondCell img").length)>0){
				secondImage=$("#secondCell img").detach();
			}
		});
		//恢复detachBtn按钮删除的图像
		$("#recoveryDetachBtn").click(function(){
			$("#secondCell").append(secondImage);
		});
		//emptyBtn按钮绑定click事件
		$("#emptyBtn").click(function(){
			$("#thirdCell").empty();
		});
	});
	</script>
</body>
</html>

在这里插入图片描述

  • 第一张图:删除后恢复的图像不再具有附加数据和click事件
  • 第二张图:删除后恢复的图像与原来一致
  • 第三张图:删除后单元格本身并没有消失
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值