加载中...

[attribute]


概述    attributeHas selector

返回值:Array<Element(s)>

描述:选择所有具有指定属性的元素,该属性可以是任何值。

  • V : 1.0jQuery( "[attribute]" )

    attribute: 一个属性名

匹配包含给定属性的元素。注意,在jQuery 1.3中,前导的@符号已经被废除!如果想要兼容最新版本,只需要简单去掉@符号即可。

示例

实例

查找所有含有 id 属性的 div 元素

HTML 代码:
  1. <div>
  2. <p>Hello!</p>
  3. </div>
  4. <div id="test2"></div>
jQuery 代码:
  1. $("div[id]")
结果:
  1. [ <div id="test2"></div> ]

实例

给具有id属性的div绑定一个单一的点击,文本中增加div的id文本。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>attributeHas demo</title>
  6. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  7. </head>
  8. <body>
  9. <div>no id</div>
  10. <div id="hey">with id</div>
  11. <div id="there">has an id</div>
  12. <div>nope</div>
  13. <script>
  14. // Using .one() so the handler is executed at most once
  15. // per element per event type
  16. $( "div[id]" ).one( "click", function() {
  17. var idString = $( this ).text() + " = " + $( this ).attr( "id" );
  18. $( this ).text( idString );
  19. });
  20. </script>
  21. </body>
  22. </html>

运行一下


还没有评论.