使用counter index设置.hover()和.mouseout()事件

时间:2014-08-18 14:41:15

标签: javascript jquery

我正在尝试使用Twitter Bootstrap 3 i jQuery制作简单的五星评级系统。现在,我试图通过编写不起作用的代码来使用计数器设置.hover()和.mouseout()事件:

var i;
for (i = 1; i <= 5; i++) {
    $('#overall_rating_' + i).hover(function(){
        $('#overall_rating_' + i).removeClass("glyphicon-star-empty").addClass("glyphicon-star");
    });
    $('#overall_rating_' + i).mouseout(function(){
        $('#overall_rating_' + i).removeClass("glyphicon-star").addClass("glyphicon-star-empty");
    });
}

尝试在鼠标悬停时突出显示当前和之前的星标。代码不完整,它将附带额外的子计数器,但这部分暂时不起作用。欢迎任何更好的方法。什么打破了?

3 个答案:

答案 0 :(得分:3)

尝试更像这样的东西

$('[id^=overall_rating_]').hover(function(){
    $(this).toggleClass("glyphicon-star-empty glyphicon-star");
});

FIDDLE


编辑以适应评论,研究所有以前的明星等。

var starz = $('[id^=overall_rating_]').hover(function(){
    starz.filter(':lt('+$(this).index()+')')
         .add(this)
         .toggleClass("glyphicon-star-empty glyphicon-star");
});

FIDDLE

答案 1 :(得分:2)

您需要向闭包i变量添加匿名函数调用:

var i;
for (i = 1; i <= 5; i++) {
    ( function( i ) {
        $('#overall_rating_'+i).hover(function(){
            $('#overall_rating_' + i).removeClass("glyphicon-star-empty").addClass("glyphicon-star");
        });
        $('#overall_rating_'+i).mouseout(function(){
            $('#overall_rating_' + i).removeClass("glyphicon-star").addClass("glyphicon-star-empty");
        });
    })( i );
}

答案 2 :(得分:1)

根据您在adeneo的回答中留下的评论,这是您真正需要的(可能会稍微优化一下):

$(".stars").hover(function() {
    $(this).removeClass("glyphicon-star-empty")
    $(this).addClass("glyphicon-star");
    $(this).prevAll().removeClass("glyphicon-star-empty")
    $(this).prevAll().addClass("glyphicon-star");
}, function() {
    $(".stars").removeClass("glyphicon-star")
    $(".stars").addClass("glyphicon-star-empty");
});

DEMO