我有基于默认值的代码,它填充了星星。例如,如果数字为3,它将使我满3星,但是jquery填充它的方式是,前两颗星为空,其余三颗为我。我有演示here。另外,如果数字为小数,如何填充半星?
HTML代码:
<p class="rating" data-default-value="2">
<!-- data-default-value="@rev.Rating" -->
<span data-value="5" class="fa fa-star"></span>
<span data-value="4" class="fa fa-star"></span>
<span data-value="3" class="fa fa-star"></span>
<span data-value="2" class="fa fa-star"></span>
<span data-value="1" class="fa fa-star"></span>
</p>
和CSS:
.rated {
border: 1px solid red;
}
.half {
border: 1px solid blue;
}
和JQuery:
jQuery(function($) {
$('.rating').each(function() {
$(this).find('span').slice(-$(this).data('defaultvalue')
).addClass("rated");
});
})
最佳答案
不使用切片(我认为它更容易阅读)
jQuery(function($) {
var count = $('.rating').data('defaultValue');
for(var i = 1; i <= count; i++)
{
$('.rating > span[data-value=' + i + ']').addClass("rated");
}
})
.rated {
border: 1px solid red;
}
.half {
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<p class="rating" data-default-value="2">
<!-- data-default-value="@rev.Rating" -->
<span data-value="1" class="fa fa-star">1</span>
<span data-value="2" class="fa fa-star">2</span>
<span data-value="3" class="fa fa-star">3</span>
<span data-value="4" class="fa fa-star">4</span>
<span data-value="5" class="fa fa-star">5</span>
</p>
如果您真的想使用
slice
,可以这样:您需要在“ 0和x之间”切片数组。如果使用单个参数调用,则只会得到切片数组的末尾部分。有关
.slice()
方法的更多信息,请参见the documentation。 jQuery(function($) {
var count = $('.rating').data('defaultValue');
$('.rating > span').slice(0, count).addClass("rated")
})
.rated {
border: 1px solid red;
}
.half {
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<p class="rating" data-default-value="2">
<!-- data-default-value="@rev.Rating" -->
<span data-value="1" class="fa fa-star">1</span>
<span data-value="2" class="fa fa-star">2</span>
<span data-value="3" class="fa fa-star">3</span>
<span data-value="4" class="fa fa-star">4</span>
<span data-value="5" class="fa fa-star">5</span>
</p>
关于javascript - 星级评定使星星从背面充满,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46733348/