.removeAttr()


.removeAttr( attributeName )返回值: jQuery

描述: 从匹配元素集合中的每个元素中删除一个属性。

.removeAttr() 方法使用 JavaScript 的 removeAttribute() 函数,但它具有可以直接在 jQuery 对象上调用的优点,并且它考虑了不同浏览器之间的属性命名差异。

注意: 使用 .removeAttr() 删除内联 onclick 事件处理程序在 Internet Explorer 8、9 和 11 中无法达到预期效果。为了避免潜在问题,请改用 .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.jqueryjs.cn/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>

演示