如何使用 jQuery 刪除除第一個元素以外的其他所有元素?


若要僅刪除第一個元素之外的所有元素,請結合使用 jQuery 中的 slice() 方法和 remove() 方法。你可以嘗試執行以下程式碼以使用 jQuery 僅移除第一個元素以外的所有元素 -

示例

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".button1").click(function(){
        $("span").remove();
    });
   
     $(".button2").click(function(){
         $('span').slice(1).remove();
     });
     
  });
</script>
</head>
<body>
<button class="button2">Hide all, except first element</button>
<button class="button1">Hide all the elements</button>

<span>
<p>This is demo text.</p>
<p>This is demo text.</p>
</span>
<span>
<p>This is demo text.</p>
<p>This is demo text.</p>
</span>
<span>
<p>This is demo text.</p>
<p>This is demo text.</p>
</span>

</body>
</html>

更新於: 14-02-2020

2K+ 檢視次數

啟動你的 職業

學完課程,獲得認證

開始
廣告
© . All rights reserved.