概述 .removeAttr( attributeName )
返回值:jQuery
描述:为匹配的元素集合中的每个元素中移除一个属性(attribute)。
String
.removeAttr() 方法使用原生的 JavaScript removeAttribute() 函数,但是它的优点是可以直接在一个 jQuery 对象上调用该方法,并且它解决了跨浏览器的属性名不同的问题。
注意: Internet Explorer 8, 9 ,和11中,使用.removeAttr()删除一个内联onclick 事件处理程序不会达到预期的效果,为了避免潜在的问题,使用 .prop()代替:
$element.prop("onclick", null);
console.log("onclick property: ", $element[0].onclick);
示例
将文档中图像的src属性删除
<img src="test.jpg"/>
$("img").removeAttr("src");
[ <img /> ]
点击按钮,添加或删除按钮后面 input 元素的 title 属性。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>removeAttr demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.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" ).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>
运行一下