加载中...

attr()


概述    .attr( attributeName )

返回值:String

描述:获取匹配的元素集合中的第一个元素的属性的值。

  • V : 1.0.attr( attributeName )

    • attributeName
      类型: String
      要获取的属性名称

.attr()方法只获取第一个匹配元素的属性值。要获取每个单独的元素的属性值, 我们需要依靠jQuery的 .each()或者.map()方法循环。

使用 jQuery的 .attr() 方法得到了一个元素的属性值主要有两个好处:

  1. 方便:它可以直接被jQuery对象访问并且链式调用其他jQuery方法。
  2. 浏览器兼容:一些属性在不同浏览器中得到不同的值。 甚至在同一个浏览器的不同版本中。 .attr() 方法减少了兼容性问题。

注意: 除少数属性意外,属性值都是字符串,如value和tabindex。

在jQuery 1.6中,当属性没有被设置时候,.attr()方法将返回undefined另外,.attr()不应该用在普通的对象,数组,窗口(window)或文件(document)上。 若要检索和更改DOM属性,比如元素的checked, selected, 或 disabled状态,请使用.prop()方法。

Attributes vs. Properties

attributesproperties之间的差异在特定情况下是很重要。jQuery 1.6之前.attr()方法在取某些 attribute 的值时,会返回 property 的值,这就导致了结果的不一致。从 jQuery 1.6 开始.prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值。

例如, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected 应使用.prop()方法进行取值或赋值。 在jQuery1.6之前,这些属性使用.attr()方法取得,但是这并不是元素的attr属性。他们没有相应的属性(attributes),只有特性(property)。

例如,考虑一个DOM元素的HTML标记中定义的<input type="checkbox" checked="checked" /> ,并假设它是一个JavaScript变量命名的elem

elem.checked true (Boolean) 将随着复选框状态的改变而改变
$(elem).prop("checked") true (Boolean) 将随着复选框状态的改变而改变
elem.getAttribute("checked") "checked" (String) 复选框的初始状态;不会改变
$(elem).attr("checked") (1.6) "checked" (String) 复选框的初始状态;不会改变
$(elem).attr("checked") (1.6.1+) "checked" (String) 将随着复选框状态的改变而改变
$(elem).attr("checked") (pre-1.6) true (Boolean) 将随着复选框状态的改变而改变

根据W3C的表单规范 ,在checked属性是一个布尔属性, 这意味着,如果这个属性(attribute)是目前存在, 即使,该属性没有对应的值,或者被设置为空字符串值,或甚至是"false",相应的属性(property)为true。 这才是真正的所有布尔属性(attributes)。

然而,要记住的最重要的概念是checked特性(attribute)不是对应它checked属性(property)。特性(attribute)实际对应的是defaultChecked属性(property),而且仅用于设置复选框最初的值。checked特性(attribute)值不会因为复选框的状态而改变,而checked属性(property)会因为复选框的状态而改变。因此,  跨浏览器兼容的方法来确定一个复选框是否被选中,是使用该属性(property):

  • if ( elem.checked )
  • if ( $(elem).prop("checked") )
  • if ( $(elem).is(":checked") )

对于其他的动态属性,同样是true,比如 selectedvalue.

Additional Notes(其他注意事项):

  • 在Internet Explorer 9之前的版本,使用.prop()设置DOM元素的属性进行赋值时,若所赋值的类型不是基本类型(number, string, 或 boolean),而且也没有使用 .removeProp() 方法在 DOM 元素从文档中被移除之前。为了安全的在 DOM 对象上进行赋值而不用担心内存泄露问题,请使用 .data() 方法 。

示例

实例

Display the checked attribute and property of a checkbox as it changes.

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>attr demo</title>
  6. <style>
  7. p {
  8. margin: 20px 0 0;
  9. }
  10. b {
  11. color: blue;
  12. }
  13. </style>
  14. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  15. </head>
  16. <body>
  17. <input id="check1" type="checkbox" checked="checked">
  18. <label for="check1">Check me</label>
  19. <p></p>
  20. <script>
  21. $( "input" )
  22. .change(function() {
  23. var $input = $( this );
  24. $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +
  25. ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +
  26. ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );
  27. })
  28. .change();
  29. </script>
  30. </body>
  31. </html>

运行一下

实例

在页面的第一个<em>中找到title属性。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>attr demo</title>
  6. <style>
  7. em {
  8. color: blue;
  9. font-weight: bold;
  10. }
  11. div {
  12. color: red;
  13. }
  14. </style>
  15. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  16. </head>
  17. <body>
  18. <p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p>
  19. The title of the emphasis is:<div></div>
  20. <script>
  21. var title = $( "em" ).attr( "title" );
  22. $( "div" ).text( title );
  23. </script>
  24. </body>
  25. </html>

运行一下

概述    .attr( attributeName, value )

返回值:jQuery

描述:设置每一个匹配元素的一个或多个属性。

  • V : 1.0.attr( attributeName, value )

    • attributeName
      类型: String
      要设置值的属性名。
    • value
      类型: String or Number or Null
      要设置的属性值。如果为null, 指定的属性将被删除(就像.removeAttr()一样)。
  • V : 1.0.attr( attributes )

    • attributes
      类型: PlainObject
      一个要设置的 属性-值 集合对象。
  • V : 1.1.attr( attributeName, function )

    • attributeName
      类型: String
      要设置值的属性名。
    • function
      类型: Function( Integer index, String attr ) => String 或者 Number
      这个函数返回用来设置的值。this指向当前的元素。接收该元素在集合中索引位置(index)和 原来属性值(attr)作为参数。

这个 .attr() 方法 是一个设置属性值的方便而且强大的途径—特别是当设置多个属性或使用值来自函数。 让我们考虑下面的图片:

  1. <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

Setting a simple attribute(设置一个简单的属性)

我们可以通过.attr()方法非常简单的改变 alt 属性并附上新值:

  1. $('#greatphoto').attr('alt', 'Beijing Brush Seller');

我们可以用同样的方法 添加 一个属性:

  1. $('#greatphoto')
  2. .attr('title', 'Photo by Kelly Clark');

Setting several attributes at once(一次设置多个属性)

同时改变alt 属性 和 添加 title属性, 我们可以使用一个“名/值”形式的对象 (JavaScript object literal)传递给这个方法。 每个 key-value 对象将增加或者修改一个属性:

  1. $('#greatphoto').attr({
  2. alt: 'Beijing Brush Seller',
  3. title: 'photo by Kelly Clark'
  4. });

当设置多个属性,包裹属性名的引号是可选的。

警告: 当设置样式名(“class”)属性时,必须使用引号!

注意: 试图改变 由document.createElement()创建的inputbutton type属性,在Internet Explorer 8或更老的版本中将抛出一个例外。

Computed attribute values(推算属性值)

通过使用一个函数来设置属性, 可以根据该元素上的其它属性值返回最终所需的属性值。例如,我们可以把新的值与现有的值联系在一起:

  1. $('#greatphoto').attr('title', function(i, val) {
  2. return val + ' - photo by Kelly Clark'
  3. });

当前运用一个函数来计算属性的值,当我们修改了多个元素的属性,特别有用。

注意 如果setter函数没有返回任何数据(例如:function(index, attr){}),属性的当前值返回值是undefined,作为一个getter行为。实际上,如果不进行任何更改的setter函数不返回的东西。

示例

实例

为页面中全部的 <img>设置一些属性。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>attr demo</title>
  6. <style>
  7. img {
  8. padding: 10px;
  9. }
  10. div {
  11. color: red;
  12. font-size: 24px;
  13. }
  14. </style>
  15. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  16. </head>
  17. <body>
  18. <img>
  19. <img>
  20. <img>
  21. <div><b>Attribute of Ajax</b></div>
  22. <script>
  23. $( "img" ).attr({
  24. src: "/resources/hat.gif",
  25. title: "jQuery",
  26. alt: "jQuery Logo"
  27. });
  28. $( "div" ).text( $( "img" ).attr( "alt" ) );
  29. </script>
  30. </body>
  31. </html>

运行一下

实例

使第二个后面的按钮disabled

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>attr demo</title>
  6. <style>
  7. div {
  8. color: blue;
  9. }
  10. span {
  11. color: red;
  12. }
  13. b {
  14. font-weight: bolder;
  15. }
  16. </style>
  17. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  18. </head>
  19. <body>
  20. <div>Zero-th <span></span></div>
  21. <div>First <span></span></div>
  22. <div>Second <span></span></div>
  23. <script>
  24. $( "div" )
  25. .attr( "id", function( arr ) {
  26. return "div-id" + arr;
  27. })
  28. .each(function() {
  29. $( "span", this ).html( "(id = '<b>" + this.id + "</b>')" );
  30. });
  31. </script>
  32. </body>
  33. </html>

运行一下

实例

通过图片的title属性设置src属性。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>attr demo</title>
  6. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  7. </head>
  8. <body>
  9. <img title="hat.gif">
  10. <script>
  11. $( "img" ).attr( "src", function() {
  12. return "/resources/" + this.title;
  13. });
  14. </script>
  15. </body>
  16. </html>
运行一下


还没有评论.