jQuery应用实例2:表格隔行换色
程序员文章站
2022-03-10 08:21:24
这里是用JS实现的:http://www.cnblogs.com/xuyiqing/p/8376312.html 接下来利用上一篇提到的选择器利用jQuery实现: 发现原来多行代码这里只需要两行:
这里是用JS实现的:http://www.cnblogs.com/xuyiqing/p/8376312.html
接下来利用上一篇提到的选择器利用jQuery实现:
发现原来多行代码这里只需要两行:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>表格隔行换色</title> <script type="text/javascript" src="js/jquery-1.8.3.js" ></script> <script> $(function(){ $("tbody>tr:even").css("background-color","pink"); $("tbody>tr:odd").css("background-color","aqua"); }); </script> <style> </style> </head> <body> <table border="1" width="500" height="50" align="center" id="tbl"> <thead> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>张三</td> <td>22</td> </tr> <tr> <td>2</td> <td>李四</td> <td>25</td> </tr> <tr> <td>3</td> <td>王五</td> <td>27</td> </tr> <tr> <td>4</td> <td>小明</td> <td>29</td> </tr> <tr> <td>5</td> <td>小红</td> <td>30</td> </tr> <tr> <td>6</td> <td>小刚</td> <td>20</td> </tr> </tbody> </table> </body> </html>View Code
更好的方式是直接为标签添加类:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>表格隔行换色</title> <script type="text/javascript" src="js/jquery-1.8.3.js" ></script> <script> $(function(){ $("tbody>tr:even").addClass("even"); $("tbody>tr:odd").addClass("odd"); }); </script> <style> .even{ background-color: pink; } .odd{ background-color: aqua; } </style> </head> <body> <table border="1" width="500" height="50" align="center" id="tbl"> <thead> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>张三</td> <td>22</td> </tr> <tr> <td>2</td> <td>李四</td> <td>25</td> </tr> <tr> <td>3</td> <td>王五</td> <td>27</td> </tr> <tr> <td>4</td> <td>小明</td> <td>29</td> </tr> <tr> <td>5</td> <td>小红</td> <td>30</td> </tr> <tr> <td>6</td> <td>小刚</td> <td>20</td> </tr> </tbody> </table> </body> </html>View Code
实际开发中是将样式写入css文件中link引入的,
这里为了方便展示写在一个文件中