我有一个 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,每个包含五个具有 .star-rating 类的图像。我想弄清楚如何定位当前事件的 .Star-Rating-Block 的特定子项。我想做到这一点,以便用户可以使用 3 个评级控件中的任何一个,而不会影响其他控件。我觉得我快要完成这个功能了,但我不确定该怎么做才能完成它。我错过了什么?
最佳答案
将当前 block 保存为变量并用作上下文:
$('.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
变量赋值的意义何在?
关于jquery - 定位当前div的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32637260/