两个相同的id,只有一个有效果
<ul id="rating" class="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 id="rating" class="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>
<script>
// 自我执行的匿名函数,不需要调用
var rating = (function() {
var lightOn = function($item,num) {
$item.each(function(index) {
if (index < num) {
$(this).css("background-position", "0 -26px");
} else {
$(this).css("background-position", "0 0");
}
});
};
var init = function(el, num) {
var $rating = $(el);
var $item = $rating.find(".rating-item");
lightOn($item,num);
//事件委托,子元素事件委托给父元素处理
$rating
.on("mouseover", ".rating-item", function() {
lightOn($item,$(this).index() + 1);
})
.on("click", ".rating-item", function() {
num = $(this).index() + 1;
})
.on("mouseout",function() {
lightOn($item,num);
});
};
//Jquery插件
$.fn.extend({
rating:function(num){
console.log(this);
return this.each(function(){
init(this,num)
});
// return init(this,num)
}
});
return{
init:init
};
})();
rating.init('#rating',3);
// $('#rating').rating(1)
</script>