将两个函数绑定到jQuery中的按钮 [英] Binding two functions to a button in jQuery

查看:80
本文介绍了将两个函数绑定到jQuery中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在单击此按钮以执行这些功能之一时,我有些麻烦.....

so I am having a little trouble with this button performing either of these functions on click.....

这不是很好,因为baseexpand和fullcollapse应该是类,但是我不够熟练以重写整个函数集以适应这一点,因为它们大约有50个依赖项.

it isn't great as baseexpand and fullcollapse should be classes but I am not skilled enough to re-write an entire set of functions to accomodate this as they have about 50 dependencies.

无论如何,这是两个功能....

Anyway to the point , here is the two functions ....

// Full collapse
$( '#fullcollapse' ).click(function(){
    $( '#menu' ).multilevelpushmenu( 'collapse' );
});

// Base expand
$( '#baseexpand' ).click(function(){
    $( '#menu' ).multilevelpushmenu( 'expand' );
});

它们展开和折叠侧边栏菜单....我有2个看起来像这样的按钮....

they expand and collapse a sidebar-menu .... i have 2 buttons that looks like this ....

    <a id="fullcollapse" class="nav-toggle" role="button" href="#"><span></span></a>

<a id="baseexpand" class="nav-toggle" role="button" href="#"><span></span></a>

我想将这些按钮变成一个切换按钮,以在每次单击的ID之间切换.

I want to make those buttons into one toggle button changing between the id's on each click.

我已经连续6个小时阅读文档,并试图对其进行研究,但无法解决这一问题.请帮助

I have been reading documentation for about 6 hours straight now and trying to look into it but am unable to solve this one. Please help

推荐答案

尝试使用此包装器编写函数

Try composing your functions with this wrapper

var toggle = function (funcA, funcB) {
    var flag = true;
    return function () {
        if (flag) {
            funcA();
        } else {
            funcB();
        }
        flag = !flag;
    };
};

应用

$('#btn').click(toggle (function (){
    $('#menu').multilevelpushmenu( 'collapse' ); // happens 1, 3, 5, 7, ...   time clicked
}, function (){
    $('#menu').multilevelpushmenu( 'expand' );   // happenes  2, 4, 6, 8, ... time clicked
}));

奖励:我重新实现了切换功能,以便能够建议返回值.

bonus I reimplemented toggle to be able to propogate a return value.

var toggle = function (a, b) {
    var togg = false;
    return function () {
        // passes return value back to caller
        return (togg = !togg) ? a() : b();
    };
};

这篇关于将两个函数绑定到jQuery中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆