在练习jQuery表格变色例子过程中,发现了一下几个问题:
- 在IEEdge浏览器中切换选中行会出现上一个表格行背景色被吃掉的情况;
- 在chrome中从上向下单击行中任意单元可以选中该行,而从下往上单击虽选中了行,而前面的按钮列未显示选中状态
针对以上问题,查阅了资料后,发现了原因,以及解决方法:
- 为tbody设置border-collapse:collapse;方可解决吃色问题
- 在引用jQuery版本是1.6之后的,设置radio的checked属性不应使用attr()方法,应使用prop()方法
在之前的jQuery版本中,都是使用attr()访问对象的属性,比如取一个图片的alt属性,就可以这样做$('#img').attr('alt');但是在某些时候,比如访问input的disabled属性时,会有些问题,在有些浏览器中,只要写了disable属性就可以,有些则要写:disabled="disabled"。所以,从1.6版本开始,jQuery使用新方法prop()获取以及设置这些属性,返回标准属性:true/false。按照官方说明,如果设置disabled和checked这些属性,应使用prop()方法(摘自《锋利的jQuery(第2版)》)
附上我的代码
- 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- 2 <html>
- 3 <head>
- 4 <title>表格变色</title>
- 5 <style type="text/css">
- 6 table{
- 7 margin:auto;
- 8 border:1px solid #ccc;
- 9 padding:20px;
- 10 text-align:left;
- 11 /*添加上border-collapse属性设置之后就可以解决在IEedge中选择不同行之后吃色的问题*/
- 12 border-collapse:collapse;
- 13 }
- 14 tr{
- 15 padding:0px;
- 16 margin:0px;
- 17 }
- 18 td{
- 19 width:100px;
- 20 padding: 0px;
- 21 }
- 22
- 23 th{
- 24 border-bottom: 1px solid #ccc;
- 25 }
- 26 /*奇数行*/
- 27 .odd{
- 28 background: #ffffee;
- 29 }
- 30 /*偶数行*/
- 31 .even{
- 32 background: #fff38f;
- 33 }
- 34
- 35 .selected{
- 36 background: gold;
- 37 color:#fff;
- 38 }
- 39 </style>
- 40 <script type="text/javascript" src="../jquery-3.4.1.js"></script>
- 41 <script type="text/javascript">
- 42 $(function(){
- 43 $("tbody>tr:odd").addClass("odd");//先排除第一行,然后给奇数行添加样式
- 44 $("tbody>tr:even").addClass("even");//先排除第一行,然后给偶数行添加样式
- 45
- 46 $('tbody>tr').click(function(){
- 47 $(this)
- 48 .addClass('selected')
- 49 .siblings().removeClass('selected')
- 50 .end()
- 51 // .find(':radio').attr("checked",true);//在设置input的checked属性的时候,使用的是jq中的attr()方法;这个方法在jquery1.6以后的版本使用的时候会出现问题,应换成prop()方法。prop()方法通常用来设置元素固有的属性,比如disabled和checked属性。
- 52 .find(':radio').prop("checked",true);
- 53 });
- 54
- 55 // 如果单选框默认情况下是选择的,则高色.
- 56 // $('table :radio:checked').parent().parent().addClass('selected');
- 57 //简化:
- 58 // $('table :radio:checked').parents("tr").addClass('selected');
- 59 //再简化:
- 60 $('tbody>tr:has(:checked)').addClass('selected');
- 61
- 62 })
- 63 </script>
- 64 </head>
- 65 <body>
- 66 <table>
- 67 <thead>
- 68 <tr><th></th><th>姓名</th><th>性别</th><th>暂住地</th></tr>
- 69 </thead>
- 70 <tbody>
- 71 <tr><td><input type="radio" name="choice" checked='checked'></td><td>张三</td><td>男</td><td>北京</td></tr>
- 72 <tr><td><input type="radio" name="choice"></td><td>李四</td><td>男</td><td>上海</td></tr>
- 73 <tr><td><input type="radio" name="choice"></td><td>王五</td><td>女</td><td>北京</td></tr>
- 74 <tr><td><input type="radio" name="choice"></td><td>小明</td><td>男</td><td>上海</td></tr>
- 75 <tr><td><input type="radio" name="choice"></td><td>韩梅梅</td><td>女</td><td>北京</td></tr>
- 76 <tr><td><input type="radio" name="choice"></td><td>大牛</td><td>男</td><td>上海</td></tr>
- 77 </tbody>
- 78 </table>
- 79 </body>
- 80 </html>
每天进步一点点