| 1. 操作属性 上文介绍了如何筛选到需要的元素。得到了元素之后就要对其进行操作。一个常见的需求是遍历得到的元素集,对每一个元素进行一个操作。jQuery提供的函数是 
 each(iterator),其中iterator是一个函数,接受一个整数作为参数,表示第几个元素。看一个简单的例子。
 
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <title>jQuery Operation</title>
 <script type="text/javascript" src="jquery-1.3.2.js"></script>
 <script type="text/javascript">
 $(function() {
 $('img').each(function(n) {
 this.alt = "This is " + n + "th picture";
 });
 });
 </script>
 </head>
 <body>
 <h1>Image Gallery<br />March 13th,2010</h1>
 <img src="img/bee.jpg" alt="" width="150px"/>
 <img src="img/bright.jpg" alt="" width="150px"/>
 <img src="img/crowd.jpg" alt="" width="150px"/>
 <img src="img/pink.jpg" alt="" width="150px"/>
 <img src="img/white.jpg" alt="" width="150px"/>
 </body>
 </html>结果用Firebug查看下:
 
 在上例中,采用了原生javascript的方法存取属性,jQuery 提供了一个更加一般的方法来存取属性,attr: 
 attr(name),如果name是字符串,获得第一个元素的属性的name的值;如果name是一个对象,则对象的属性被作为元素的属性而复制到包装集的所有元素上。
 
 attr(name,value),当name是字符串的时候,就把属性name的值设置为value,当value是一个函数的时候,则对包装集中的每个元素调用此函数,将其name的值设置为函数的返回值。
 
 看一个简单的例子,html代码仍然使用上面的:
 
 <scripttype="text/javascript">
 $(function() {
 $('body').children().attr('title', function(n) {
 return"This is "+ n + "th element";
 });
 $('img').attr('alt', 'A photo taken by YinZixin');
 alert($('h1').attr('title'));
 });
 </script>
 
 结果为:
 
 要删除属性,使用removeAttr(name)方法。                         (编辑:宣城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |