遇到混合点击和悬停事件的问题。
单击一个非事件的 li a 元素会切换一个事件的类并绑定(bind)一个悬停事件。 将鼠标悬停在现在事件的元素上会显示一个以前隐藏的 block (span.rate) 单击悬停元素应该将其隐藏,删除悬停事件并切换父级上的事件类,使其不再“事件”。
单击悬停事件不会删除事件并切换为事件状态。关于互斥选项,还有一些其他逻辑,但这一切都很好。
jsfiddle 说明它们是如何组合在一起的:
当前的js:
ps = {
psToggle: 0,
init: function () {
$(document).ready(function () {
$('.example li a)').on('click', function(e) {
e.preventDefault();
var that = $(this);
if (that.parent().hasClass('paired')) {
if (rm.psToggle === 0) {
that.toggleClass('active');
that.find('.rate').fadeToggle(50);
rm.psToggle = 1;
} else {
if (that.hasClass('active')) {
that.toggleClass('active');
that.find('.rate').fadeToggle(50);
rm.psToggle = 0;
} else {
$('.paired a').toggleClass('active');
that.find('.rate').fadeToggle(50);
//Call message function
}
}
rm.pControl();
} else {
that.toggleClass('active');
that.find('.rate').fadeToggle(50);
rm.pControl();
}
});
});
},
pControl: function () {
//Unbind events to all control items excluding 1st item.
$('.example li a').off('hover');
$('.example li a .rate').off('click');
$('.example .active').each(function(i) {
$(this).on('hover', function() {
$(this).find('.rate').fadeToggle(50);
});
});
$('.example li a.active .rate').on('click', function() {
//Remove hover/hide and toggle active state
$(this).off('hover');
$(this).hide();
$(this).parent().toggleClass('active');
rm.pControl(); //rebind new active classes
});
}
};
ps.init();
最佳答案
查看以下演示。
两个点击事件都被触发了,因为 ,.rate
是 a
的子级。
$('.example li a.active .rate').on('click'...
和
$('.example li a').on('click'...
- 因此您可以删除对
.rate
的点击。 <强> Demo1 或者给 child 添加
e.stopPropagation();
来停止从 parent 到 child 的事件冒泡。 <强> Demo2$('.example li a.active .rate').on('click', function(e) { e.stopPropagation(); //Remove hover/hide and toggle active state $(this).off('hover'); $(this).hide(); $(this).parent().toggleClass('active'); ps.pControl(); //rebind new active classes });
关于javascript - 添加和删除单击/悬停事件处理程序 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24277395/