将事件绑定在父元素上,格式$(父元素).on("事件名称","子元素选择器",function(方法体){})
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>星级评分</title> <script src="js/jquery-1.11.3.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){
var num = 2; // 点亮 function lightOn(num){ $(".star-item").each(function(index){ if(index < num){ $(this).css("background-position","0 -70px"); }else{ $(this).css("background-position","0 0"); } }) } lightOn(num); //mouseover和click事件 $("#group1").on("mouseover",".star-item",function(){//利用事件冒泡,将事件绑定在父元素上(事件委托) lightOn($(this).index() + 1); }).on("click",".star-item",function(){ num = $(this).index() + 1; lightOn(num); }).on("mouseout",function(){ lightOn(num); }) }) </script> <style type="text/css"> *{ margin: 0; padding: 0; } li { list-style: none; } .star { width: 350px; height: 350px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; border: 1px solid red; } .star-grounp { display: block; width: 350px; height: 70px; } .star-item { display: inline-block; width: 60px; height: 60px; float: left; margin-right: 10px; background: url(img/star.jpg) no-repeat; cursor: pointer; } </style> </head> <body> <div class="star"> <ul class="star-grounp" id="group1"> <li class="star-item" title="很不好"></li> <li class="star-item" title="不好"></li> <li class="star-item" title="一般"></li> <li class="star-item" title="好"></li> <li class="star-item" title="很好"></li> </ul> </div> </body> </html>