为什么我的 if 语句仅在我的输入具有值时才有效

Why is my if statement only work when my input has a value?

本文关键字:我的 有效 输入 if 语句 为什么      更新时间:2023-09-26

我正在使用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>

j查询:

$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)

它按预期工作。