当您将鼠标悬停在星图标上时,恒星的类应更改,当单击时,应修复星数。脚本中有一个错误,不允许这样做。
$('.comment-form-stars [data-fa-i2svg]').on('mouseover', function () {
var onStar = parseInt($(this).data('value'), 10);
$(this).parent().children('[data-fa-i2svg]').each(function (e) {
if (e < onStar) {
$(this).removeClass('far');
$(this).addClass('fas');
} else {
$(this).removeClass('fas');
$(this).addClass('far');
}
});
}).on('mouseout', function () {
if (!ratingVal || ratingVal == 0) {
$(this).parent().children('[data-fa-i2svg]').each(function (e) {
$(this).removeClass('far');
$(this).addClass('fas');
});
} else {
$(this).parent().children('[data-fa-i2svg]').each(function (e) {
var r = parseInt($(this).data('value'), 10);
if (r < ratingVal) {
$(this).removeClass('far');
$(this).addClass('fas');
}
});
}
});
.fa-star {
color: #f8c31d;
cursor: pointer;
}
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.7.2/js/all.js"></script>
<div class="comment-form-stars">
<i class="fas fa-star" aria-hidden="true" data-value="1"></i>
<i class="far fa-star" aria-hidden="true" data-value="2"></i>
<i class="far fa-star" aria-hidden="true" data-value="3"></i>
<i class="far fa-star" aria-hidden="true" data-value="4"></i>
<i class="far fa-star" aria-hidden="true" data-value="5"></i>
</div>
您尝试在Fontawesome将它们注入页面之前尝试绑定到图标。通过与父div结合并使用事件委托来避免这种情况,如下所述:
$('.comment-form-stars').on('mouseover', '[data-fa-i2svg]', function () {
var onStar = parseInt($(this).data('value'), 10);
$(this).parent().children('[data-fa-i2svg]').each(function (e) {
if (e < onStar) {
$(this).removeClass('far');
$(this).addClass('fas');
} else {
$(this).removeClass('fas');
$(this).addClass('far');
}
});
}).on('mouseout', '[data-fa-i2svg]', function () {
if (!ratingVal || ratingVal == 0) {
$(this).parent().children('[data-fa-i2svg]').each(function (e) {
$(this).removeClass('far');
$(this).addClass('fas');
});
} else {
$(this).parent().children('[data-fa-i2svg]').each(function (e) {
var r = parseInt($(this).data('value'), 10);
if (r < ratingVal) {
$(this).removeClass('far');
$(this).addClass('fas');
}
});
}
});
.fa-star {
color: #f8c31d;
cursor: pointer;
}
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.7.2/js/all.js"></script>
<div class="comment-form-stars">
<i class="fas fa-star" aria-hidden="true" data-value="1"></i>
<i class="far fa-star" aria-hidden="true" data-value="2"></i>
<i class="far fa-star" aria-hidden="true" data-value="3"></i>
<i class="far fa-star" aria-hidden="true" data-value="4"></i>
<i class="far fa-star" aria-hidden="true" data-value="5"></i>
</div>