jQuery的remove()方法使用详解
remove()方法的定义和用法:
此方法将会从DOM中删除所有匹配的元素。
说明:remove()方法不会把匹配的元素从jQuery对象中删除,因而可以在将来再使用这些匹配的元素,不过除了这个元素本身得以保留之外,其他的比如绑定的事件,附加的数据等都会被移除。
语法结构:
$(selector).remove(expr)
参数列表:
参数 描述
expr 可选。用于筛选元素的jQuery表达式
实例代码:
<!DOCTYPEhtml> <html> <head> <metacharset="utf-8"> <scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script> <scripttype="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("div").remove("#first"); }) }) </script> </head> <body> <divid="first">我是第一</div> <divid="second">我是第二</div> <button>点击</button> </body> </html>
以下代码能够删除div集合中id为first的div。
<!DOCTYPEhtml> <html> <head> <metacharset="utf-8"> <scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script> <scripttype="text/javascript"> $(document).ready(function(){ $("#btd").click(function(){ $("div").remove(); }) }) </script> </head> <body> <divid="first">我是第一</div> <divid="second">我是第二</div> <buttonid="btd">点击删除第一个div</button> </body> </html>
如果省略参数,那就是删除所有匹配的元素。
<!DOCTYPEhtml> <html> <head> <metacharset="utf-8"> <styletype="text/css"> div{ width:200px; height:200px; border:5pxsolidgreen; } </style> <scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script> <scripttype="text/javascript"> $(document).ready(function(){ $("#btd").click(function(){ vara=$("div"); a.remove("#first"); $("#btn").click(function(){ alert(a.length); }) }) }) </script> </head> <body> <divid="first">我是第一</div> <divid="second">我是第二</div> <buttonid="btd">删除第一个div</button><buttonid="btn">查看删除操作后div的数量</button> </body> </html>
remove()已经将DOM中的匹配元素删除,但是并没有将它从jquery对象中删除。
jquery使用remove()方法删除指定class子元素的方法
<!DOCTYPEhtml> <html> <head> <scriptsrc="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").remove(".italic"); }); }); </script> </head> <body> <p>Thisisaparagraphinthediv.</p> <pclass="italic"><i>Thisisanotherparagraphinthediv.</i></p> <pclass="italic"><i>Thisisanotherparagraphinthediv.</i></p> <button>Removeallpelementswithclass="italic"</button> </body> </html>
看到这段代码之后,我想不用我过多的解释了。大家就明白了吧,很有意思的方法。