jQuery中删除元素/内容

597 阅读1分钟

清空内容

empty();从被选元素中删除子元素

清空内容不推荐使用元素.html("");该方法可能会使元素删除,而元素绑定的事件没删除,从而造成内存泄漏。

删除元素

remove(); 删除被选元素(及其子元素)

表格删除练习:

7.png

<!DOCTYPE html>

<html>

	<head lang="en">
		<meta charset="UTF-8">
		<title></title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}
			
			.wrap {
				width: 410px;
				margin: 100px auto 0;
			}
			
			table {
				border-collapse: collapse;
				border-spacing: 0;
				border: 1px solid #c0c0c0;
			}
			
			th,
			td {
				border: 1px solid #d0d0d0;
				color: #404060;
				padding: 10px;
			}
			
			th {
				background-color: #09c;
				font-weight: bold;
				font-size: 16px;
				color: #fff;
			}
			
			td {
				font-size: 14px;
			}
			
			td a.get {
				text-decoration: none;
			}
			
			a.del:hover {
				text-decoration: underline;
			}
			
			tbody tr {
				background-color: #f0f0f0;
			}
			
			tbody tr:hover {
				cursor: pointer;
				background-color: #fafafa;
			}
			
			#btn {
				width: 110px;
				height: 30px;
				font-size: 20px;
				font-weight: bold;
			}
		</style>

	</head>

	<body>
		<div class="wrap">
			<input type="button" value="清空内容" id="btn">
			<table>
				<thead>
					<tr>
						<th>课程名称</th>
						<th>所属学院</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody id="j_tb">
					<tr>
						<td>JavaScript</td>
						<td>前端与移动开发学院</td>
						<td>
							<a href="#" class="get">DELETE</a>
						</td>
					</tr>
					<tr>
						<td>css</td>
						<td>前端与移动开发学院</td>
						<td>
							<a href="#" class="get">DELETE</a>
						</td>
					</tr>
					<tr>
						<td>html</td>
						<td>前端与移动开发学院</td>
						<td>
							<a href="#" class="get">DELETE</a>
						</td>
					</tr>
					<tr>
						<td>jQuery</td>
						<td>前端与移动开发学院</td>
						<td>
							<a href="#" class="get">DELETE</a>
						</td>
					</tr>
				</tbody>
			</table>
		</div>

		<script src="js/jquery.js"></script>
		<script>
			$(function() {
				//1. 找到清空按钮,注册点击事件,清空tbody
				$("#btn").on("click", function() {
					$("#j_tb").empty();
				});

				//2. 找到delete,注册点击事件。删除tr
				$(".get").on("click", function() {
					$(this).parent().parent().remove();
				});

			});
		</script>

	</body>

</html>