本节书摘来自异步社区《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行利用当前元素的类名和索引值组合成一个新的名字,以便演示函数的功能。然而这个例子在实践中可能用处不大。