【发布时间】:2016-02-23 02:08:28
【问题描述】:
我正在使用 jQuery 构建一个五星级评级系统。该脚本创建五个星形图标。当您将鼠标悬停在其中一个上时,将突出显示之前以及包括悬停在其上的星的所有星。当您单击星号时,脚本创建的隐藏输入的值将更改为该星号以及该星号以及该星号以及该星号之前的星号,直到单击其他星号为止。当用户的鼠标离开星的父级时,如果先前选择了星(基于隐藏输入的值),则这些星保持突出显示。如果用户的鼠标离开父级时之前没有选择任何星,所有星都将返回为空...或者它们应该。
目前,当鼠标离开父级时,星星会返回选择,这就是我想要的。问题是如果没有选择一个值(没有点击星号),星号不会变回空。父级的mouseleave方法中的if语句有什么问题?这是jsFiddle。我已将输入保留为文本输入,因此您可以看到值的变化。
HTML:
<div class="rating" style="float: none;clear: both;">
<noscript>
<label class="radio-inline">
<input type="radio" name="stars" value="1" title="1 Star"> 1
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="2" title="2 Stars"> 2
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="3" title="3 Stars"> 3
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="4" title="4 Stars"> 4
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="5" title="5 Stars"> 5
</label>
</noscript>
</div>
jQuery:
$element = $('.rating');
$element.each(function() {
$element.empty();
var hiddenInput = $('<input type="text" name="stars" id="selectedStars">');
$element.append(hiddenInput);
$selectedStars = $('#selectedStars').val();
for (var i = 0; i < 5; i++) {
var occurrence = i + 1;
var newStar = $('<i class="fa fa-star-o" title="' + occurrence + ' stars" data-occurrence="' + occurrence + '"></i>');
newStar.on('click', function() {
$('#selectedStars').attr('value', $(this).data('occurrence'));
$(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
$(this).nextAll().removeClass('fa-star').addClass('fa-star-o');
$element.data('selected', $(this).data('occurrence'));
console.log($selectedStars);
}).on('mouseover', function() {
$(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
$(this).nextAll().removeClass('fa-star').addClass('fa-star-o');
});;
$element.append(newStar);
}
$(this).mouseleave(function() {
$selectedStars = $('#selectedStars').attr('value');
if ($selectedStars != '') {
$('i[data-occurrence="' + $selectedStars + '"]').prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
$('i[data-occurrence="' + $selectedStars + '"]').nextAll().removeClass('fa-star').addClass('fa-star-o');
console.log($selectedStars);
} else {
//This should return all stars to empty if no value was set.
$('i[class*="fa-star"]').removeClass('fa-star').addClass('fa-star-o');
}
});
});
【问题讨论】:
标签: javascript jquery