<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>星级评分--第一种实现方式</title> <script src="jquery.min.js"></script> <style> body,ul,li{ padding:0; margin:0; } li{ list-style-type:none; } .rating{ width:175px; height:35px; margin:100px auto; } .rating-item{ float:left; width:35px; height:35px; background:url(image/01.jpg) no-repeat; cursor:pointer; } </style> <script> var rating=(function() { var lightOn = function ($item,num) { $item.each(function (index) { if (index < num) { $(this).css('background-position', '0 -36px'); } else { $(this).css('background-position', '0 0'); } }); }; var init = function (el, num) { var $rating = $(el); $item = $rating.find('rating-item'); lightOn($item, num); $rating.on('mouseover', 'rating-item', function () { lightOn($(this).index() + 1); }).on('click', 'rating-item', function () { num = $(this).index() + 1; }).on('mouseout', function () { lightOn(num); }); }; $.fn.extend({ rating:function(num){ return this.each(function(){ init(this,num); }); } }); return { init: init }; })(); rating.init('#rating',2); // rating.init('#rating2',3) $('#rating2').rating(4); </script> </head> <body> <ul class="rating" id="rating"> <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> </body> </html>
$item = $rating.find('rating-item');
这个语句也要改成:$item = $rating.find('.rating-item');
事件委托绑定$rating.on('mouseover', 'rating-item',内,应该是 '.rating-item'。