欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  .attr( attributeName, value )
  
  描述: 设置每一个匹配元素的一个或多个属性。
  
  attr( attributeName, value )
  
  attributeName
  
  类型: String
  
  要设置值的属性名
  
  value
  
  类型: String,Number
  
  这个属性设置的值
  
  attributes
  
  类型: PlainObject
  
  一个 属性 - 值 集合对象。(译者注:例如{ alt: '', title: 'WEB前端开发-http://www.css88.com })
  
  attributeName
  
  类型: String
  
  要设置值的属性名.
  
  function(index, attr)
  
  类型: Function()
  
  这个函数返回用来设置的值,this指向当前的元素。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。
  
  这个 .attr() 方法 是一个设置属性值的方便而且强大的途径—特别是当设置多个属性或使用值来自函数。 让我们考虑下面的图片:
  
  <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />
  
  Setting a simple attribute(设置一个简单的属性)
  
  我们可以通过.attr()方法非常简单的改变 alt 属性并附上新值:
  
  $('#greatphoto').attr('alt', 'Beijing Brush Seller');
  
  我们可以用同样的方法 添加 一个属性:
  
  $('#greatphoto')
  
  .attr('title', 'Photo by Kelly Clark');
  
  Setting several attributes at once(一次设置多个属性)
  
  同时改变alt 属性 和 添加  title属性, 我们可以使用一个“名/值”形式的对象 (JavaScript object literal)传递给这个方法。 每个 key-value 对象将增加或者修改一个属性:
  
  $('#greatphoto').attr({
  
  alt: 'Beijing Brush Seller',
  
  title: 'photo by Kelly Clark'
  
  });
  
  当设置多个属性,包裹属性名的引号是可选的。
  
  警告: 当设置样式名(“class”)属性时,必须使用引号!
  
  注意: jQuery禁止改变一个 <input> 或 <button>元素的type 特性(attribute),并且在所有浏览器下将抛出一个错误。因为Internet Explorer不会允许你改变<input>或者<button>元素的type属性。
  
  Computed attribute values(推算属性值)
  
  通过使用一个函数来设置属性, 可以根据该元素上的其它属性值返回最终所需的属性值。例如,我们可以把新的值与现有的值联系在一起:
  
  $('#greatphoto').attr('title', function(i, val) {
  
  return val + ' - photo by Kelly Clark'
  
  });
  
  当前运用一个函数来计算属性的值,当我们修改了多个元素的属性,特别有用。
  
  注意 如果setter函数没有返回任何数据(例如:function(index, attr){}),属性的当前值返回值是undefined,作为一个getter行为。实际上,如果不进行任何更改的setter函数不返回的东西。
  
  例子:
  
  Example: 为页面中全部的 <img>设置一些属性。
  
  <!DOCTYPE html>
  
  <html>
  
  <head>
  
  <style>
  
  img { padding:10px; }
  
  div { color:red; font-size:24px; }
  
  </style>
  
  <script src="https://code.jquery.com/jquery-latest.js"></script>
  
  </head>
  
  <body>
  
  <img />
  
  <img />
  
  <img />
  
  <div><B>Attribute of Ajax</B></div>
  
  <script>
  
  $("img").attr({
  
  src: "images/hat.gif",
  
  title: "jQuery",
  
  alt: "jQuery Logo"
  
  });
  
  $("div").text($("img").attr("alt"));
  
  </script>
  
  </body>
  
  </html>

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h63988.shtml