jQuery remove() 方法



jQuery 中的 remove() 方法用於從 DOM 中移除所有選定的元素。它會將元素及其資料和所有繫結的事件處理程式一起移除。

如果我們想移除元素而不移除資料和事件,我們需要使用 detach() 方法。

如果我們只想移除選定元素中的內容,我們需要使用 empty() 方法。

語法

以下是 jQuery 中 remove() 方法的語法:

$(selector).remove(expr)

引數

此方法接受以下可選引數:

  • selector: 用於篩選要移除的匹配元素集的選擇器表示式。只有匹配此表示式的元素才會被移除。

示例 1

在下面的示例中,我們使用 remove() 方法移除所有 <div> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("div").remove();
    });
  });
</script>
</head>
<body>
<div>Div element 1.</div>
<div>Div element 2.</div>
<button>Remove all "div" elements</button>
</body>
</html>

單擊按鈕時,所有“div”元素都將被移除。

示例 2

在此示例中,我們使用 remove() 方法的可選引數來移除具有類名“one”的 <div> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("div").remove(".one");
    });
  });
</script>
</head>
<body>
<div>Div element 1.</div>
<div>Div element 2.</div>
<div class="one">Div element 3 (with class "one").</div>
<div class="one">Div element 4 (with class "one").</div>
<button>Remove all "div" elements</button>
</body>
</html>

單擊按鈕時,所有具有類名“one”的 <div> 元素都將被移除。

示例 3

在這裡,我們使用可選引數來篩選要移除的多個元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("div").remove(".one, .two");
    });
  });
</script>
</head>
<body>
<div>Div element 1.</div>
<div>Div element 2.</div>
<div class="one">Div element 3 (with class "one").</div>
<div class="one">Div element 4 (with class "one").</div>
<div class="two">Div element 5 (with class "two").</div>
<button>Remove all "div" elements</button>
</body>
</html>

單擊按鈕時,它將移除所有具有類名“one”和“two”的“div”元素。

jquery_ref_html.htm
廣告
© . All rights reserved.