×

jQuery的remove()方法使用详解

作者:Terry2017.01.03来源:Web前端之家浏览:1407评论:0
关键词:JQueryJSjavascript

remove()方法的定义和用法:

此方法将会从DOM中删除所有匹配的元素。

说明:remove()方法不会把匹配的元素从jQuery对象中删除,因而可以在将来再使用这些匹配的元素,不过除了这个元素本身得以保留之外,其他的比如绑定的事件,附加的数据等都会被移除。

语法结构:

$(selector).remove(expr)

参数列表:

参数 描述
expr 可选。用于筛选元素的jQuery表达式

实例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
 $("button").click(function(){
  $("div").remove("#first");
 })
})
</script> 
</head>
<body>
<div id="first">我是第一</div>
<div id="second">我是第二</div>
<button>点击</button>
</body>
</html>

以下代码能够删除div集合中id为first的div。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
 $("#btd").click(function(){
  $("div").remove();
 })
})
</script> 
</head>
<body>
<div id="first">我是第一</div>
<div id="second">我是第二</div>
<button id="btd">点击删除第一个div</button>
</body>
</html>

如果省略参数,那就是删除所有匹配的元素。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
div{
 width:200px;
 height:200px;
 border:5px solid green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
 $("#btd").click(function(){
  var a=$("div");
  a.remove("#first");
  $("#btn").click(function(){
   alert(a.length);
  })
 })
})
</script> 
</head>
<body>
<div id="first">我是第一</div>
<div id="second">我是第二</div>
<button id="btd">删除第一个div</button><button id="btn">查看删除操作后div的数量</button>
</body>
</html>

remove()已经将DOM中的匹配元素删除,但是并没有将它从jquery对象中删除。

jquery使用remove()方法删除指定class子元素的方法

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js">
</script>
<script>
$(document).ready(function(){
 $("button").click(function(){
 $("p").remove(".italic");
 });
});
</script>
</head>
<body>
<p>This is a paragraph in the div.</p>
<p class="italic"><i>This is another paragraph in the div.</i></p>
<p class="italic"><i>This is another paragraph in the div.</i></p>
<button>Remove all p elements with class="italic"</button>
</body>
</html>

看到这段代码之后,我想不用我过多的解释了。大家就明白了吧,很有意思的方法。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/svg1483372800834.html

网友评论文明上网理性发言 已有0人参与

发表评论: