<script type="text/javascript">
var rating = (function(){
//点亮整颗
var lightEntire = function(el,options){
this.$el = $(el);
this.$item = this.$el.find('.rating-item');
this.opts = options;
};
lightEntire.prototype.init = function(){
this.lightOn(this.opts.num);
if(!this.opts.readOnly){
this.bindEvent();
}
};
lightEntire.prototype.lightOn = function(num){
num = parseInt(num);
this.$item.each(function(index){
if(index < num){
$(this).css('background-position','0 -40px')
}else{
$(this).css('background-position','1px 0')
}
});
};
lightEntire.prototype.bindEvent = function(){
var self = this;
var itemLength = self.$item.length;
//事件绑定
self.$el.on('mousemove','.rating-item',function(){
var num = $(this).index() + 1;
self.lightOn(num);
//短路写法,只有&&前面的成立,才能执行后面的代码
(typeof self.opts.selected === 'function') && self.opts.selected.call(this,num,itemLength);
//在父容器上触发一个事件
self.$el.trigger('selected',[num,itemLength]);
}).on('click','.rating-item',function(){
self.opts.num = $(this).index() + 1 ;
//短路写法,只有&&前面的成立,才能执行后面的代码
(typeof self.opts.chosen === 'function') && self.opts.selected.call(this,self.opts.num,itemLength);
//在父容器上触发一个事件
self.$el.trigger('chosen',[self.opts.num,itemLength]);
}).on('mouseout',function(){
self.lightOn(self.opts.num);
})
};
//默认参数
var defaults = {
num:0,
readOnly:false,//是否只读
selected:function(){},
chosen:function(){}
}
//初始化
var init = function(el,options){
options = $.extend({},defaults,options);//用户传递参数时,使用传递参数,options的内容覆盖defalts。生成的内容存在空对象里。
new lightEntire(el,options).init();
}
return {
init:init
}
})();
rating.init('#rating',{
num:2,
// selected:function(num,total){
// console.log(num+'/'+ total)
// },
})
$('#rating').on('selected',function(e,num,total){
console.log(num+'/'+ total)
}).on('chosen',function(e,num,total){
console.log(num+'/'+ total)
})
</script>
西小勺说得对
mouseover打成了mousemove