jQuery 刪除元素和屬性
在本教程中,你將學習如何使用 jQuery 從文件中刪除 HTML 元素或其內容及其屬性。
jQuery 刪除元素或內容
jQuery 提供很多方法,如 empty() 、 remove() 和 unwrap() 等等,以除去從文件現有的 HTML 元素或內容。
jQuery empty() 方法
jQuery empty() 方法從 DOM 中刪除所有子元素以及其他後代元素和所選元素中的文字內容。
以下示例將在單擊按鈕時刪除 .container 元素內的所有內容。
<script type="text/javascript">
$(document).ready(function(){
// Empty container element
$("button").click(function(){
$(".container").empty();
});
});
</script>
注意: 根據 W3C(全球資訊網聯盟)DOM 規範,元素中的任何文字字串都被視為該元素的子節點。
jQuery remove() 方法
jQuery remove() 方法從 DOM 中刪除所選元素以及其中的所有內容。除了元素本身之外,還刪除了與元素關聯的所有繫結事件和 jQuery 資料。
以下示例將在按鈕單擊時從 DOM 中刪除具有 .hint 類的所有 <p> 元素。這些段落中的巢狀元素也將被刪除。
<script type="text/javascript">
$(document).ready(function(){
// Removes paragraphs with class "hint" from DOM
$("button").click(function(){
$("p.hint").remove();
});
});
</script>
jQuery remove() 方法還可以包含一個選擇器作為可選引數,允許你過濾要刪除的元素。例如,前面的示例的 jQuery DOM 刪除程式碼可以重寫如下:
<script type="text/javascript">
$(document).ready(function(){
// Removes paragraphs with class "hint" from DOM
$("button").click(function(){
$("p").remove(".hint");
});
});
</script>
注意: 你還可以將選擇器表示式作為引數包含在 jQuery remove() 方法中, remove(".hint, .demo") 以便過濾多個元素。
jQuery unwrap() 方法
jQuery unwrap() 方法從 DOM 中刪除所選元素的父元素。這通常是 wrap() 方法的反轉。
以下示例將在按鈕單擊時刪除 <p> 元素的父元素。
<script type="text/javascript">
$(document).ready(function(){
// Removes the paragraph's parent element
$("button").click(function(){
$("p").unwrap();
});
});
</script>
jQuery removeAttr() 方法
jQuery removeAttr() 方法從所選元素中刪除屬性。
下面的示例將單擊按鈕時刪除 <a> 元素的 href 屬性。
<script type="text/javascript">
$(document).ready(function(){
// Removes the hyperlink's href attribute
$("button").click(function(){
$("a").removeAttr("href");
});
});
</script>