加载中...

removeAttr()


概述    .removeAttr( attributeName )

返回值:jQuery

描述:为匹配的元素集合中的每个元素中移除一个属性(attribute)。

  • V : 1.0.removeAttr( attributeName )

    • attributeName
      类型: String
      要移除的属性名,从1.7版本开始,它可以是一个空格分隔的属性列表。

.removeAttr() 方法使用原生的 JavaScript removeAttribute() 函数,但是它的优点是可以直接在一个 jQuery 对象上调用该方法,并且它解决了跨浏览器的属性名不同的问题。

注意: Internet Explorer 8, 9 ,和11中,使用.removeAttr()删除一个内联onclick 事件处理程序不会达到预期的效果,为了避免潜在的问题,使用 .prop()代替:

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

示例

实例

将文档中图像的src属性删除

HTML 代码:
  1. <img src="test.jpg"/>
jQuery 代码:
  1. $("img").removeAttr("src");
结果:
  1. [ <img /> ]

实例

点击按钮,添加或删除按钮后面 input 元素的 title 属性。

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

运行一下


还没有评论.