繁体   English   中英

如何覆盖(?)一个jQuery事件?

[英]How to overwrite(?) a jQuery event?

我现在已经为此工作了好几天,但我仍然无法弄清楚。

我使用jQuery构建了一个滑出菜单,它可以正常工作。 关键是,我希望将其打开的菜单按钮也应将其关闭。

我所要做的是默认情况下将菜单按钮设置为类.inactive,然后设置单击事件处理程序以打开菜单,然后从元素中删除类“ .inactive”并添加类“ .active”。 '。 然后我做了另一个功能,与此相反。 问题是,第一个事件运行正常,但是第二个事件却没有。 菜单打开,jQuery编辑HTML的样式,但是当我再次单击该按钮时,样式将保持不变。

有没有办法覆盖第一个事件以便执行第二个事件? 抱歉,如果我缺少真正的基本解决方案,那么请使用以下脚本:

$(document).ready(function(){

    $('.inactive').click(function() {
        do_animations();
        //'.menu-button i' below is the menu button which gets the active/inactive classes//
        $('.menu-button i').addClass('active');
        $('.menu-button i').removeClass('inactive');
    });

    $('.active').click(function() {
        do_animations();
        $('.menu-button i').addClass('inactive');
        $('.menu-button i').removeClass('active');
    });
});

如果需要它们,我可以提供代码的所有详细信息,但这是重要的部分,以免使时间太长。 我确定所有语法都是正确的,并且在开发人员工具中没有出现任何错误。

您可以在此处使用事件委托。 这样的事情应该起作用:

$(document).ready(function(){
    //body will work but preferably the container of these elements would be best
    $('body').on('click', '.inactive', function() {
        do_animations();
        //'.menu-button i' below is the menu button which gets the active/inactive classes//
        $('.menu-button i').addClass('active');
        $('.menu-button i').removeClass('inactive');
    });

    $('body').on('click', '.active', function() {
        do_animations();
        $('.menu-button i').addClass('inactive');
        $('.menu-button i').removeClass('active');
    });
});

可以这样说:当在任何地方单击身体时。 检查该元素是否具有.inactive类,如果有,请调用该函数。

先前的解决方案是这样说的:在页面中找到所有元素,并在这些元素上注册此回调。 因此,当它搜索带有.active标签的元素时,没有发现任何元素。 它没有注册回调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM