【问题标题】:prevAll including first element in jQueryprevAll 包括 jQuery 中的第一个元素
【发布时间】:2016-02-22 04:49:06
【问题描述】:

我目前正在编写一个五星级评级系统的脚本。我有一行 5 个很棒的星形图标。当鼠标悬停在一颗星星上时,那颗星星和它后面的星星应该变成满星星而不是空星星。我目前正在使用 prevAll 将更改应用于星星,但它不适用于第一颗星星......假设因为如果它是第一颗星星,则没有“prev”星星适用于 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。

【问题讨论】:

标签: jquery


【解决方案1】:

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

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 delegation,因为您通过替换htmlevent delegation 将元素动态附加到div.rating将事件附加到div.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2020-11-22
    • 2018-09-23
    • 2023-04-08
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多