如何使用 jQuery 刪除 HTML 元素的所有屬性?


要刪除 HTML 元素的所有屬性,removeAttr() 方法行不通。為此,建立一個數組,然後使用 removeAllAttrs() 來刪除特定 HTML 元素的所有屬性。例如,透過刪除 img 元素的屬性來刪除影像。

你可以嘗試執行以下程式碼來了解如何從元素中刪除所有屬性。我們正在刪除 img 元素屬性 −

示例

線上演示

<html>
   <head>
      <title>Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {
            $(".remove-attr").click(function(){  
              $.fn.removeAllAttrs= function() {
                 return this.each(function() {
                    $.each(this.attributes, function() {
                      this.ownerElement.removeAttributeNode(this);
                    });
                 });
               };
            $('img').removeAllAttrs();
          });
         });
      </script>
   </head>
   <body>
      <button type="button" class="remove-attr">Remove Image</button>
      <img src="/green/images/logo.png” alt=”MyImage”>
   </body>
</html>

更新於: 13-Feb-2020

逾 1K 次瀏覽

開啟你的 職業生涯

完成此課程以獲得認證

開始
廣告
© . All rights reserved.