<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>星级评分之第一种写法</title>
<style>
body, ul, li {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
.rating {
width: 250px;
height: 30px;
margin: 100px auto;
}
.rating-item {
display: inline-block;
width: 30px;
height: 30px;
background:url(images/xj1.jpg) no-repeat;
cursor: pointer;
}
</style>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<ul class="rating" id="rating1">
<li class="rating-item" title="十分不好"></li>
<li class="rating-item" title="不好"></li>
<li class="rating-item" title="一般"></li>
<li class="rating-item" title="十分不好"></li>
<li class="rating-item" title="很好"></li>
</ul>
<ul class="rating" id="rating2">
<li class="rating-item" title="十分不好"></li>
<li class="rating-item" title="不好"></li>
<li class="rating-item" title="一般"></li>
<li class="rating-item" title="十分不好"></li>
<li class="rating-item" title="很好"></li>
</ul>
<ul class="rating" id="rating3">
<li class="rating-item" title="十分不好"></li>
<li class="rating-item" title="不好"></li>
<li class="rating-item" title="一般"></li>
<li class="rating-item" title="十分不好"></li>
<li class="rating-item" title="很好"></li>
</ul>
<script>
var rating=(function(){
// 点亮
var lightOn = function($item,num) {
$item.each(function(index) {
if(index < num) {
$(this).css('background-position', '0 -30px');
} else {
$(this).css('background-position', '0 0');
}
});
};
var init=function(el,num){
//缓存、jQuery对象与DOM对象
var $rating = $(el)
$item = $rating.find('.rating-item');
// 初始化
lightOn($item,num);
// 事件绑定
$rating.on('mouseover','.rating-item',function() {
console.log($(this).index());
lightOn($item,$(this).index() + 1);
}).on('click','.rating-item', function() {
num = $(this).index() + 1;
}).on('mouseout', function() {
lightOn($item,num);
});
};
return{
init:init
};
})();
rating.init("#rating1",2);
rating.init("#rating2",1);
rating.init("#rating3",3);
</script>
</body>
</html>
找到问题了,给出答案,真的是细节问题:
var $rating = $(el);//两个var分别申明变量的话,这边是分号
var $item = $rating.find(".rating-item");
或者用一个var申明两个变量,就是用逗号
var $rating = $(el),//逗号
$item = $rating.find(".rating-item");
解决了,落个逗号