《jQuery、jQuery UI及jQuery Mobile技巧与示例》——3.3 技巧:生成类名

本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.3节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看

3.3 技巧:生成类名

addClass()函数的参数可以不是静态字符串。可以传入一个函数,如代码清单3-3所示。这在动态Web应用程序中尤其方便。但要小心:除了必需的CSS样式外,不要把它搞得太复杂。使用适当的选择器,不使用麻烦的类名就可以做很多的事情。

代码清单3-3 向addClass()传入函数

00 <!DOCTYPE html>
01 
02 <html lang="en">
03 <head>
04  <title>A function as argument to addClass()</title>
05  <style>
06  /* 请将下列代码移至一个外部的
07    .css文件*/
08   
09  p.changed-0 {
10   background-color: green;
11  }
12  
13  p.differentchanged-1 {
14   background-color: blue;
15  }
16  
17  p.twochanged-2 {
18   background-color: red;
19  }
20  
21  </style>
22 </head>
23 <body>
24 
25 <p>This text will have a different appearance 
26  after the class change</p>
27 <p class="different">This text will have a different 
28  appearance after the class change</p>
29 <p class="one two">This text will have a different 
30  appearance after the class change</p>
31 <div>This text will not change</div>
32 
33 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
34 
35 <script>
36 // 请将下列代码移至一个外部的.js文件中
37 $(document).ready(function() {
38 
39  $('p').addClass(function(index, className) {
40    $(this).removeClass();
41    return className + 'changed-' + index;
42   });
43  
44 });
45 </script>
46 </body>
47 </html>

在第39行,函数的index参数表示选取集中的元素索引值,className参数表示当前元素的类名。第41行利用当前元素的类名和索引值组合成一个新的名字,以便演示函数的功能。然而这个例子在实践中可能用处不大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值