如何使用 jQuery 刪除下一個元素?


要刪除 jQuery 中的下一個元素,可以使用 remove()。

示例

以下為程式碼 −

 線上演示

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <div name="cancelDivision">
      <div style="color:red;">
         <span class="demo1">cancel(X)</span>
         Demo
      </div>
      <hr>
      <div style="color:gren;">
         <span class="demo1">cancel(X)</span>
         Demo
      </div>
      <hr>
      <div style="color:skyblue;">
         <span class="demo1">cancel(X)</span>
         Demo
      </div>
      <hr>
      </div>
   </div>
</body>
<script>
   $(".demo1").click(function () {
      $(this).parent().next("hr").remove();
      $(this).parent().remove();
      return false;
   });
</script>
</html>

要執行上述程式,請儲存檔名“anyName.html(index.html)”。右鍵單擊檔案,然後在 VSCode 編輯器中選擇“Live Server”選項 −

輸出

這將產生以下輸出 −

每當您單擊取消(X)時,jQuery 將刪除元素。這將產生以下輸出 −

更新時間: 2020 年 11 月 9 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程可獲得認證

開始
廣告
© . All rights reserved.