evastar.js 2 KB
/**
* Evaluate Star
* Code in 2014/11/10
* By van
*/

define( 'evastar' ,function( require, exports, module ){
    var evastar = function( target, options ){
		this.target = target;
		this.o = {
			area: 'eva-stars-click',
			starElement: '<i></i>',
			showtag: "<span></span>",
			inputname: 'ihidden',
			number: 5,
			recode: ["一星","二星","三星","四星","五星"],
			closeStar: 'grey',
			openStar: 'yellow',
            callback: function(){}
		}
		
		this.o = $.extend( this.o, options );
		
		this.init();
	};
	evastar.prototype = {
		init: function(){
			this.makeHtml();
			this.starListener();
		},
		//对于指定评价星星区域添加所需html内容
		makeHtml: function(){
			var $_this = $(this.target);
			if ( $_this.length > 0 ){
				for ( var i=0;i < this.o.number;i++ ){
					var star = $(this.o.starElement);
          star.attr('title', this.o.recode[i]);
          star.attr('class', "targetstar");
					star.appendTo( $(this.target) );
				}
				$(this.o.input).appendTo( $_this );
				$('<input type="hidden">').addClass(this.o.inputname).appendTo( $_this );
				$(this.o.showtag).insertAfter( $_this );
			}
		},
		//评价星星事件监听集合
		starListener: function(){
			var _this = this,
			result = 0;
		
			$(this.target).find( /\w+/.exec(this.o.starElement)[0] )
			.bind({
				mouseenter: function(){
					_this.change( $(this).index()+1 );
				},
				mouseleave: function(){
					_this.change( result );
				},
				click: function(){
					$(this).parent().next().html( $(this).attr("title") );
					result = $(this).index()+1;
					
					_this.change( result );
					_this.record( result )
                    _this.o.callback() && 1;
				}
			});
		},
		//依据点击的星星标签索引值改变选中状态。
		change: function( n ){
			$(this.target).attr("class", this.o.area).addClass( "stars"+(n) );
		},
		//将点击的评分录入隐藏input标签中。
		record: function( n ){
			$(this.target).find( "."+this.o.inputname ).attr( "value",n );
		}
	};
	
    return evastar;
});