超级简单的评分功能,分为四个步骤轻松搞定:
第一步:
引入jquery文件;这里我用百度CDN的jquery:
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
第二步:
写HTML代码;这里的星星我用的是符号的星星,也可以做成图片,用2张背景图片进行切换:
1 <div class="score_star">
2 <i>★</i>
3 <i>★</i>
4 <i>★</i>
5 <i>★</i>
6 <i>★</i>
7 <p>您还未评价</p>
8 </div>
第三步:
写CSS样式;这里我为了方便把样式写在head里面:
1 <style type="text/css">
2 .score_star {text-align: center;}
3 .score_star i {color: #999;font-size: 28px;font-style: normal;cursor: pointer;}
4 .score_star i.on {color: #c8a377;}
5 </style>
第四步:
写JavaScript代码;好了,打瞌睡的童鞋抬起头,灯光照过来,往死里照,要画重点了:
重点是slice(0,1)方法,就是选中重第0个到第1个,第一个数字是从0开始算起,第二个数字是从1开始算起的。
1 <script type="text/javascript">
2 $(function(){
3 // 星星选择评价事件
4 $(".score_star >i").click(function(event) {
5 // 点击当前
6 var _index = $(this).index();
7 // 所有的星星
8 var i = $(this).parent().find("i");
9 i.removeClass("on");
10 // 点击第i个,第一个到i个添加类名on
11 switch(_index){
12 case 0:
13 i.slice(0,1).addClass("on");
14 $(this).siblings('p').html("我有一个退货想和你谈谈");
15 break;
16 case 1:
17 i.slice(0,2).addClass("on");
18 $(this).siblings('p').html("已被99%人超越");
19 break;
20 case 2:
21 i.slice(0,3).addClass("on");
22 $(this).siblings('p').html("只能说一般般");
23 break;
24 case 3:
25 i.slice(0,4).addClass("on");
26 $(this).siblings('p').html("骚年还不错");
27 break;
28 case 4:
29 i.slice(0,5).addClass("on");
30 $(this).siblings('p').html("一见钟情");
31 break;
32 default:
33 alert("少年醒醒,你的代码出bug了");
34 break;
35 }
36 });
37 });
38 </script>
最后,整个代码为:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>简易-星星评分-功能-jQuery纯手写</title>
6 <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
7 <style type="text/css">
8 .score_star {text-align: center;}
9 .score_star i {color: #999;font-size: 28px;font-style: normal;cursor: pointer;}
10 .score_star i.on {color: #c8a377;}
11 </style>
12 </head>
13 <body>
14 <div class="score_star">
15 <i>★</i>
16 <i>★</i>
17 <i>★</i>
18 <i>★</i>
19 <i>★</i>
20 <p>您还未评价</p>
21 </div>
22 <script type="text/javascript">
23 $(function(){
24 // 星星选择评价事件
25 $(".score_star >i").click(function(event) {
26 // 点击当前
27 var _index = $(this).index();
28 // 所有的星星
29 var i = $(this).parent().find("i");
30 i.removeClass("on");
31 // 点击第i个,第一个到i个添加类名on
32 switch(_index){
33 case 0:
34 i.slice(0,1).addClass("on");
35 $(this).siblings('p').html("我有一个退货想和你谈谈");
36 break;
37 case 1:
38 i.slice(0,2).addClass("on");
39 $(this).siblings('p').html("已被99%人超越");
40 break;
41 case 2:
42 i.slice(0,3).addClass("on");
43 $(this).siblings('p').html("只能说一般般");
44 break;
45 case 3:
46 i.slice(0,4).addClass("on");
47 $(this).siblings('p').html("骚年还不错");
48 break;
49 case 4:
50 i.slice(0,5).addClass("on");
51 $(this).siblings('p').html("一见钟情");
52 break;
53 default:
54 alert("少年醒醒,你的代码出bug了");
55 break;
56 }
57 });
58 });
59 </script>
60 </body>
61 </html>
点击展示所有代码
怎么样,是不是很简单?