我目前正在为五星级评级系统编写脚本。我有一行 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)
})
将 mouseover
和 mouseout
事件附加到包含 class-fa-star
的 i
元素,并遵循 event delegate
在这里,因为您通过替换 html
动态地将元素附加到 div. rating
,即通过附加事件来替换 event delegate
到div. rating
多重评级功能更新
$('.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)
})
})
关于jquery - prevAll 包括 jQuery 中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35545994/