根据单击的元素更改变量

时间:2014-10-30 22:51:15

标签: javascript jquery object var

可以更改基于元素的变量内部函数是用户点击吗? 在我的情况下,这将完全适用于一种菜单,但我需要两个完全相同的菜单 有一点不同 - 第二次单击处理程序必须加载toggleDrawer并将$ sidebar更改为$ navbar变量。

    /*
    Variables
    */

    var $sidebar = $('#sidebar'),  
        $navbar = $('#navbar'),
        drawerOpen = false,

    /*
    Functions
    */

    closeDrawer = function() {
        drawerOpen = false;
        $body.css('overflow','').removeClass('sidebar-open');
        $sidebar.removeClass('open');
        $sidebar.animate({'right':'-50%'},{duration:300});
        $(this).hide();

    },

    openDrawer = function() {
        drawerOpen = true;
        $body.addClass('sidebar-open').css('overflow','hidden');
        $sidebar.addClass('open');
        $sidebar.animate({'right':'0%'},{duration:300});                
    },

    toggleDrawer = function() {
        if (drawerOpen) {
            closeDrawer();
        }else{
            openDrawer();
        }
    },

    /*
    Bind Events
    */

    $document.on('click', '.drawer-toggle-sidebar', function(event){
        toggleDrawer();
        event.preventDefault();
    });

    $document.on('click', '.drawer-toggle-navbar', function(event){
        toggleDrawer();
        event.preventDefault();
    });

1 个答案:

答案 0 :(得分:1)

详细说明上述评论,并举例说明:

以下是传递要打开/关闭的元素的功能:



/*
    Functions
    */

    closeDrawer = function(drawer) {
        drawerOpen = false;
        $body.css('overflow','').removeClass('sidebar-open');
        drawer.removeClass('open');
        drawer.animate({'right':'-50%'},{duration:300});
        $(this).hide();

    },

    openDrawer = function(drawer) {
        drawerOpen = true;
        $body.addClass('sidebar-open').css('overflow','hidden');
        drawer.addClass('open');
        drawer.animate({'right':'0%'},{duration:300});                
    },

    toggleDrawer = function(drawer) {
        if (drawerOpen) {
            closeDrawer(drawer);
        }else{
            openDrawer(drawer);
        }
    },




你的绑定事件:



/*
    Bind Events
    */

    $document.on('click', '.drawer-toggle-sidebar', function(event){
        toggleDrawer(event.currentTarget);
        event.preventDefault();
    });

    $document.on('click', '.drawer-toggle-navbar', function(event){
        toggleDrawer(event.currentTarget);
        event.preventDefault();
    });




您甚至可以将点击事件中的两个组合成一个,然后传入currentTarget。

我希望这会有所帮助。