.removeAttr()


.removeAttr( attributeName )傳回:jQuery

說明:移除匹配元素集合中每個元素的屬性。

.removeAttr() 方法使用 JavaScript removeAttribute() 函式,但它的優點是可以直接在 jQuery 物件上呼叫,並且它會考量不同瀏覽器的不同屬性命名方式。

注意:在 Internet Explorer 8、9 和 11 中,使用 .removeAttr() 移除內嵌 onclick 事件處理常式無法達到預期的效果。為避免潛在問題,請改用 .prop()

1
2
$element.prop( "onclick", null );
console.log( "onclick property: ", $element[ 0 ].onclick );

範例

按一下按鈕會變更旁邊輸入欄位的標題。將滑鼠指標移到文字輸入欄位上,查看加入和移除標題屬性的效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>removeAttr demo</title>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<button>Change title</button>
<input type="text" title="hello there">
<div id="log"></div>
<script>
(function() {
var inputTitle = $( "input" ).attr( "title" );
$( "button" ).on( "click", function() {
var input = $( this ).next();
if ( input.attr( "title" ) === inputTitle ) {
input.removeAttr( "title" )
} else {
input.attr( "title", inputTitle );
}
$( "#log" ).html( "input title is now " + input.attr( "title" ) );
});
})();
</script>
</body>
</html>

示範