添加和删除点击/悬停事件处理程序

Adding and removing click/hover event handlers jQuery

本文关键字:悬停 事件处理 程序 删除 添加      更新时间:2023-09-26

遇到点击和悬停事件混合的问题。

单击一个不活动的元素会切换一个活动的类并绑定一个悬停事件。悬停在当前活动的元素上,将显示先前隐藏的块(span.rate)点击悬停元素应该隐藏它,删除悬停事件,并切换父元素上的活动类,使其不再是"活动"。

单击悬停事件不会删除事件并切换为活动状态。这里有一些关于互斥选项的其他逻辑,尽管这些都工作得很好。

http://jsfiddle.net/65yY3/15/

当前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 ();

检查下面的演示。

两个点击事件都被触发,因为.ratea的子事件。

$('.example li a.active .rate').on('click'...

$('.example li a').on('click'...

  • 所以你可以删除点击.rate Demo1
  • 或者在子进程中添加e.stopPropagation();来阻止从父进程到子进程的事件冒泡。以及接下来

    $('.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
    });
    

输入链接描述

$('.example li a') instead of $('.example li a)')