jquery - prevAll 包括 jQuery 中的第一个元素

标签 jquery

我目前正在为五星级评级系统编写脚本。我有一行 5 个非常棒的星形图标。当鼠标悬停在一颗星星上时,该星星及其后面的星星应该变成完整的星星,而不是空的星星。我目前正在使用 prevAll 将更改应用于星星,但它不适用于第一个星星...假设因为如果它是第一个星星,则没有“上一个”星星可应用于 prevAll()。另外,当我将鼠标从星星上移开时,我想将它们恢复到原始状态,但是当我在 mouseout 方法中设置 html 时,它会删除它们。有一个更好的方法吗?有没有我没有想到的解决方法?这是jsFiddle展示。感谢您抽出时间。

<div class="rating">
  <i class="fa fa-star-o"></i>
  <i class="fa fa-star-o"></i>
  <i class="fa fa-star-o"></i>
  <i class="fa fa-star-o"></i>
  <i class="fa fa-star-o"></i>
</div>


$('.rating').each(function() {
    $element = $(this);
  console.log(originalStars);
  $(this).find('[class*="fa-star"]').each(function() {
    console.log('star icon found.');
    $(this).mouseover(function() {
        var stars = $(this).prevAll().length;
        $(this).prevAll().each(function() {
          $(this).removeClass('fa-star-o');
          $(this).addClass('fa-star');
        });
        $(this).nextAll().each(function(){
            $(this).removeClass('fa-star');
          $(this).addClass('fa-star-o');
        });
      });
  });
  var originalStars = $element.html();  
  $element.mouseleave(function(){
    $element.html(originalStars);
    console.log('mouse left element');
  });
});

更新:设法在 mouseleave 上恢复原始星星,但一旦发生这种情况,悬停效果将不再适用。我已经在这里和 jsfiddle 中更新了 jquery。

最佳答案

这是您可以做的简单事情..

var originalStars = $('.rating').html();
$('.rating').on('mouseover','i[class*=" fa-star"]',function(){
    $(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
}).mouseout(function(){
    $(this).closest('.rating').html(originalStars)
})

mouseovermouseout 事件附加到包含 class-fa-stari 元素,并遵循 event delegate 在这里,因为您通过替换 html 动态地将元素附加到 div. rating,即通过附加事件来替换 event delegatediv. rating

<强> Single Rating DEMO


多重评级功能更新

$('.rating').each(function(){
    var _parent=$(this);
    var originalStars = _parent.html();
    $(_parent).on('mouseover','i[class*=" fa-star"]',function(){
      $(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
    }).mouseout(function(){
        $(_parent).html(originalStars)
    })
})

<强> Multiple rating DEMO

关于jquery - prevAll 包括 jQuery 中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35545994/

相关文章:

javascript - 如何根据输入有条件地隐藏输入表单的某些部分?

jQuery 在 1 秒后更改 CSS

jquery - 具有数据属性的 HTML 选项元素。是否可能,如果可能,如何使用 jQuery 检索值?

javascript - 如何检查 2 个 jQuery 选择器是否指向相同的元素?

javascript - Typeahead.js Bloodhound 忽略高质量结果

php - 有没有办法通过 JavaScript 设置 php 变量

javascript - 同位素附加似乎不起作用

javascript - 具有多种类型复选框的数据表

javascript - 使用 url 图像填充输入

jquery - 存储 DIV 元素的原始父元素