您的位置 首页 技术专栏

jquery怎么删除html标签

24小时课堂在线收录jquery怎么删除html标签,删除方法:1、用remove()方法,语法“$(selector).remove()”;2、用detach()方法,语法“$(selecto…感谢您关注jquery怎么删除html标签。

删除方法:1、用remove()方法,语法“$(selector).remove()”;2、用detach()方法,语法“$(selector).detach()”;3、用empty()方法,语法“$(selector).empty()”。

本教程操作环境:windows7系统、jquery1.7.2版本、Dell G3电脑。

在 jQuery 中,想要删除元素,我们有以下 3 种方法:remove()、detach( ) 和 empty( )。

remove()方法

在 jQuery 中,我们可以使用 remove( ) 方法来将某个元素及其内部的所有内容删除。

语法:$(selector).remove()

示例:

<!DOCTYPE html><html><head><meta charset=”UTF-8″><script src=”js/jquery-1.7.2.min.js”></script> <script> $(function () { $(“#btn”).cpck(function () { $(“p:nth-child(4)”).remove(); }) }) </script></head><body> <ul> <p>HTML</p> <p>CSS</p> <p>JavaScript</p> <p>jQuery</p> <p>Vue.js</p> </ul> <input id=”btn” type=”button” value=”删除” /></body></html>

jquery怎么删除html标签

detach( ) 方法

在 jQuery 中,detach() 和 remove() 的功能虽然相似,都是将某个元素及其内部所有内容删除,但是两者也有明显的区别。

remove() 方法用于“彻底”删除元素。所谓的“彻底”,指的是不仅会删除元素,还会把元素绑定的事件删除;

detach() 方法用于“半彻底”删除元素。所谓的“半彻底”,指的是只会删除元素,不会把元素绑定的事件删除。

语法:$(selector).detach()

示例:

<!DOCTYPE html><html><head><meta charset=”UTF-8″><script src=”js/jquery-1.7.2.min.js”></script><script type=”text/javascript”>$(document).ready(function() {$(“button”).cpck(function() {$(“p”).detach();});});</script></head><body><p>这是一个p元素段落</p><button>删除 p 元素</button></body></html>

jquery怎么删除html标签

<!DOCTYPE html><html><head><meta charset=”UTF-8″><script src=”js/jquery-1.7.2.min.js”></script><script>$(function () { $(“p”).cpck(function () { alert(“欢迎来到24小时课堂在线!”) }); $(“#btn”).cpck(function () { var $p = $(“p:nth-child(4)”).remove(); $($p).appendTo(“ul”); }); }) </script></head><body><ul><p>HTML</p><p>CSS</p><p>JavaScript</p><p>jQuery</p><p>Vue.js</p></ul><input id=”btn” type=”button” value=”删除” /></body></html>

jquery怎么删除html标签

在这个例子中,我们为每一个 p 元素添加一个点击事件,点击任何一个 p 元素都会弹出一个对话框。在我们点击【删除】按钮后,<p>jQuery</p> 这一项就会被添加到 ul 元素内部的末尾处。但是这个时候,如果再去点击 <p>jQuery</p> 这一项,会发现之前绑定的点击事件被删除了,并不会弹出对话框。当我们把 remove() 替换成 detach() 后,可以发现 p 元素被删除后又重新被添加使用时,该元素之前绑定的点击事件依然存在。对于 remove() 和 detach() 这两个方法,可以总结为这一点:元素被删除后又重新被添加,如果不希望该元素保留原来绑定的事件,应该用 remove() 方法;如果希望该元素保留原来绑定的事件,应该使用 detach() 方法。

empty( )方法

在 jQuery 中,我们可以使用 empty() 方法来“清空”某个后代元素。

语法:$(selector).empty()

示例:

<!DOCTYPE html><html><head><meta charset=”UTF-8″><script src=”js/jquery-1.7.2.min.js”></script><script>$(function () { $(“#btn”).cpck(function () { $(“ul p:nth-child(4)”).empty(); }); }) </script></head><body><ul><p>HTML</p><p>CSS</p><p>JavaScript</p><p>jQuery</p><p>Vue.js</p></ul><input id=”btn” type=”button” value=”删除” /></body></html>

jquery怎么删除html标签

以上就是jquery怎么删除html标签的详细内容,更多请关注24小时课堂在线其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/97201.html

为您推荐

返回顶部