jQuery - 刪除元素

刪除元素/內容

如需刪除元素和內容,一般可使用以下兩個jQuery 方法:

remove() - 刪除被選元素(及其子元素)

empty() - 從被選元素中刪除子元素


#remove() 方法

jQuery remove() 方法刪除被選元素及其子元素。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").remove();
  });
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:200px;border:1px solid black;background-color:pink;">
你好
<p>你很好</p>
<p>你太好了</p>
</div>
<br>
<button>移除</button>
</body>
</html>

empty() 方法

jQuery empty() 方法刪除被選元素的子元素。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").empty();
  });
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:200px;border:1px solid black;background-color:yellow;">
你好
<p>你很好</p>
<p>你太好了</p>
</div>
<br>
<button>清空</button>
</body>
</html>

過濾已刪除的元素

jQuery remove() 方法也可接受一個參數,讓您可以將刪除元素篩選。

此參數可以是任何 jQuery 選擇器的語法。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").remove(".italic");
  });
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<p class="italic"><i>这是另外一个段落。</i></p>
<p class="italic"><i>这是另外一个段落。</i></p>
<button>移除所有  class="italic" 的 p 元素。</button>
</body>
</html>


#
繼續學習
||
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php(php.cn)</title>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("input:button").click(function() {
$("input:checkbox:checked").next().nextAll().remove();
});
})
</script>
<style type="text/css">
div.box{width:300px;height:200px;padding:10px 20px;border:4px dashed #ccc;}
div.box>span{color:#999;font-style:italic;}
div.content{width:250px;height:100px;margin:10px 0;border:1px solid green;}
input{margin:10px;}
input[type='button']{width:200px;height:35px;margin:10px;border:2px solid #ebbcbe;}
</style>
</head>
<body>
<div class="box">
<span></span><br>
<div class="content">
<input type="checkbox" name="item"><span></span>
<input type="checkbox" name="item"><span></span>
<input type="checkbox" name="item"><span></span><br>
<input type="checkbox" name="item"><span></span>
<input type="checkbox" name="item"><span></span>
<input type="checkbox" name="item"><span></span><br>
</div>
<input type="button" value="">
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
图片放大关闭