jQuery 删除元素包含remove()会删除元素及其子元素,并移除相关的事件和数据。detach()类似,但保留数据和事件,适合以后重新插入。empty()则清空子元素,保留父元素。此外,unwrap()可以移除父元素,保留子元素,而hide()只是隐藏元素。涵盖 remove()、detach()、empty() 等方法。
1. 使用 remove() 删除元素
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><div id="container"><p id="p1">段落 1</p><p class="target">段落 2(带 class)</p><p>段落 3</p></div><button id="btnRemove">删除元素</button><script>$(document).ready(function () {// 点击按钮删除指定元素$("#btnRemove").click(function () {// 删除 id 为 p1 的元素$("#p1").remove();// 删除所有 class 为 target 的 <p> 元素$("p").remove(".target");});});</script></body></html>
2. 使用 detach() 临时移除元素
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><div id="container"><p id="p2">可移除的段落</p></div><button id="btnDetach">移除</button><button id="btnReattach">重新插入</button><script>$(document).ready(function () {let $detachedElement;// 移除元素并保留数据和事件$("#btnDetach").click(function () {$detachedElement = $("#p2").detach(); // 脱离 DOM});// 重新插入元素$("#btnReattach").click(function () {$("#container").append($detachedElement); // 重新添加到 DOM});});</script></body></html>
3. 使用 empty() 清空子元素
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><div id="list"><ul><li>项目 1</li><li>项目 2</li><li>项目 3</li></ul></div><button id="btnEmpty">清空列表</button><script>$(document).ready(function () {// 清空 #list 中的所有子元素$("#btnEmpty").click(function () {$("#list").empty(); // 保留 #list 容器,但删除内部内容});});</script></body></html>
4. 使用 unwrap() 移除父元素
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><div id="wrapper"><p>需要移除父元素的段落</p></div><button id="btnUnwrap">移除父元素</button><script>$(document).ready(function () {// 移除 <p> 的父元素(即 #wrapper),保留 <p> 本身$("#btnUnwrap").click(function () {$("p").unwrap(); // 移除 #wrapper,但保留 <p> 内容});});</script></body></html>
5. 根据条件删除元素
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><ul id="items"><li data-type="fruit">苹果</li><li data-type="vegetable">胡萝卜</li><li data-type="fruit">香蕉</li></ul><button id="btnFilter">删除水果</button><script>$(document).ready(function () {// 删除所有 data-type 为 fruit 的 <li>$("#btnFilter").click(function () {$("li[data-type='fruit']").remove();});});</script></body></html>