javascript - 我想在 JavaScript 中创建星级。
问题描述
我想在 JavaScript 中创建一个默认值为 5 的星级评分,我将降至 1,但我不明白如何从 1 填充到 5。
这是我的代码:-
$(".star").click(function(){
var starselect = $(this).attr("id");
for( var j = 5 ; j>starselect ; j--)
{
$("#"+j).removeClass("starchecked");
}
if( j < starselect+1 ){
$("#"+j).addClass("starchecked");
}
$(".review-star").attr("data-rating",starselect);
});
解决方案
根据我的评论,我会使用 css 来执行此操作,但如果您需要使用 js,那么我会使用nextAll
,prevAll
和andSelf
- 的混合使用,请参阅代码中的注释
var $stars = $(".star")
$stars.click(function() {
var $star = $(this);
if ($star.hasClass('checked')) {
// if current clicked star is checked
if ($star.next().hasClass('checked')) {
// check if next star is also checked
$star.nextAll().removeClass('checked'); // if next is then disable all following
} else {
$star.nextAll().andSelf().removeClass('checked'); // if not then disable self and all after (shouldn't need all after, but just in case)
}
$star.prevAll().addClass('checked'); // check all before
// if you just want to remove all stars on click of an already checked box, remove the above 2 lines and just ue the below:
// $stars.removeClass('checked');
} else {
$star.nextAll().removeClass('checked'); // remove checked from all following the clicked
$star.prevAll().andSelf().addClass('checked'); // add checked to this and all previous
}
var starselect = $stars.index($star) + 1; // get current star rating
$(".review-star").attr("data-rating", starselect);
console.log(starselect);
});
.star {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.checked {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star">1</span>
<span class="star">2</span>
<span class="star">3</span>
<span class="star">4</span>
<span class="star">5</span>
推荐阅读
- node.js - 超过 30 秒的请求返回错误的标头,浏览器抛出 CORS 错误
- sql - 使用 SQL 链接表
- performance - 在应用程序中存储图像以减少 mb 的最佳实践
- c# - 实现通过二级索引hashkey查询DynamoDb的高级方法
- javascript - 使用 JavaScript 进行客户端验证
- c# - XAML 元素在高于相机高度时消失
- python - 如何在二维布尔数组中获取相同值的子区域
- c# - 如何使用 SQLite 数据库在 C# 中填充组合框?
- android - 使用 Spotify API 的 Android 应用程序仅在调试模式下工作
- elasticsearch - ElasticSearch Filebeat 输出到现有索引