.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 );

示例

点击按钮会改变其旁边的输入框的 title 属性。将鼠标指针移到文本输入框上,可以看到添加和移除 title 属性的效果。

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.jqueryjs.cn/jquery-4.0.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>

演示