jQuery removeAttr() 方法



jQuery 中的 removeAttr() 方法用於從 DOM 中選定的元素中刪除一個或多個屬性。

此方法接受一個名為 “attribute” 的引數,該引數指定要刪除的 HTML 元素屬性的名稱。

語法

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

$(selector).removeAttr(attribute)

引數

此方法接受以下引數:

  • attribute: 表示要刪除的屬性名稱的字串。

注意: 要刪除多個屬性,需要用空格分隔屬性名稱。

示例 1

在以下示例中,我們使用 removeAttr() 方法從 <div> 元素中刪除 “style” 屬性:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        $('div').removeAttr('style');
    });
});
</script>
</head>
<body>
<div style="background-color: yellow; width:220px; border: 2px solid black;">This is a div with some styling.</div>
<button>Remove Style Attribute</button>
</body>
</html>

當我們點選按鈕時,<div> 元素的樣式將被刪除。

示例 2

在此示例中,我們從 “input” 元素中刪除多個屬性:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        $('input').removeAttr('readonly placeholder');
    });
});
</script>
</head>
<body>
<input type="text" readonly placeholder="Enter your name">
<button>Remove Attributes</button>
</body>
</html>

當我們點選按鈕時,它會從 ‘input’ 元素中刪除多個屬性(‘readonly’ 和 ‘placeholder’)。

jquery_ref_html.htm
廣告

© . All rights reserved.