如何使用 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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP