removeAttr()
为匹配的元素集合中的每个元素中移除一个属性(attribute)。
- .removeAttr(attributeName)
- attributeName类型: String要移除的属性名,从1.7版本开始,它可以是一个空格分隔的属性列表。
.removeAttr()
方法使用原生的 JavaScript removeAttribute()
函数,但是它的优点是可以直接在一个 jQuery 对象上调用该方法,并且它解决了跨浏览器的属性名不同的问题。
注意: Internet Explorer 6, 7 ,或8中,使用.removeAttr()
删除一个内联onclick
事件处理程序没有实现,为了避免潜在的问题,使用.prop()
代替:
$element.prop("onclick", null); console.log("onclick property: ", $element[0].onclick);
例子
点击按钮,添加或删除按钮后面 input 元素的 title 属性。
<!DOCTYPE html> <html> <head> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <button>Enable</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>