我有这个代码在基于默认值的地方,它填补了星星。例如,如果数字是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");
});
})
答案 0 :(得分:1)
不使用切片(我认为它更容易阅读)
jQuery(function($) {
var count = $('.rating').data('defaultValue');
for(var i = 1; i <= count; i++)
{
$('.rating > span[data-value=' + i + ']').addClass("rated");
}
})
&#13;
.rated {
border: 1px solid red;
}
.half {
border: 1px solid blue;
}
&#13;
<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>
&#13;
如果确实想要使用slice
,您可以这样做:
你需要切割数组&#34;在0和x之间#34;如果使用单个参数调用,则只获得切片数组的末尾部分。有关.slice()
方法的详细信息,请参阅the documentation。
jQuery(function($) {
var count = $('.rating').data('defaultValue');
$('.rating > span').slice(0, count).addClass("rated")
})
&#13;
.rated {
border: 1px solid red;
}
.half {
border: 1px solid blue;
}
&#13;
<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>
&#13;