[英]Why is my if statement only work when my input has a value?
我正在使用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');
}
});
});
如果沒有被選中, $selectedStars
是undefined
,而不是''
。 如果你改變
if ($selectedStars != '') {
至
if ($selectedStars)
它按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.