我有一个5星评级控件设置如下:
$('.Star-Rating-Block').each(function() {
$('.star-rating').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('star-hover');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('star-hover');
}
).click(function() {
$('.star-rating').removeClass('star-select'); // Removes the selected class from all of them
$(this).prevAll().andSelf().addClass('star-select').removeClass('star-hover'); // Adds the selected class to just the one you clicked
var rating = $(this).data('Star-Rating-Block');
});
});
不幸的是,有3个单独的.Star-Rating-Block div,每个div包含5个带有.star-rating类的图像。我试图弄清楚如何针对当前活跃的.Star-Rating-Block中的特定孩子。我想这样做,以便用户可以使用3个评级控件中的任何一个而不会影响其他控件。我觉得我已接近完成功能,但我不确定如何完成它。我错过了什么?
答案 0 :(得分:1)
将当前块保存为变量并用作上下文:
$('.Star-Rating-Block').each(function() {
var container = this;
$('.star-rating', container).hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('star-hover');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('star-hover');
}
).click(function() {
$('.star-rating', container).removeClass('star-select'); // Removes the selected class from all of them
$(i).prevAll().andSelf().addClass('star-select').removeClass('star-hover'); // Adds the selected class to just the one you clicked
var rating = $(this).data('Star-Rating-Block');
});
});
请注意$(i)
,因为您还没有在任何地方定义i
...
但是,不需要each
:
$('.Star-Rating-Block .star-rating').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('star-hover');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('star-hover');
}
).click(function() {
var container = $(this).closest('.Star-Rating-Block');
$('.star-rating', container).removeClass('star-select'); // Removes the selected class from all of them
$(i).prevAll().andSelf().addClass('star-select').removeClass('star-hover'); // Adds the selected class to just the one you clicked
var rating = $(this).data('Star-Rating-Block');
});
仍然不确定$(i)
或者为从未使用过的本地rating
变量赋值是什么意思?