0

我有两个类似的功能通过页面上的句柄执行响应式菜单切换,请参阅代码:

//responsive main navigation
    $(function() {
        var pull        = $('#pull');
            menu        = $('.main-nav ul');
            menuHeight  = menu.height();

        $(pull).on('click', function(e) {
            e.preventDefault();
            menu.slideToggle('fast');
        });
    });

    //responsive blog navigation
    $(function() {
        var toggle        = $('#toggle-handle');
            sidebar        = $('.blog-sidebar-wrap');
            sidebarHeight  = sidebar.height();

        $(toggle).on('click', function(e) {
            e.preventDefault();
            sidebar.slideToggle('fast');
        });
    });

我的问题是我怎样才能写这个,这样我就不会重复同样的过程(函数)。我是否设置了一个函数并传入参数?非常感谢您的帮助,这里的 jQuery/Javascript 初学者!

4

2 回答 2

5

尝试

//a function that creates a slide based menu
function slideMenu(ctrl, target){
    ctrl.on('click', function(e) {
        e.preventDefault();
        target.slideToggle('fast');
    });
}

//responsive main navigation
$(function() {
    var pull        = $('#pull');
    menu        = $('.main-nav ul');
    menuHeight  = menu.height();

    slideMenu(pull, menu)
});

//responsive blog navigation
$(function() {
    var toggle        = $('#toggle-handle');
    sidebar        = $('.blog-sidebar-wrap');
    sidebarHeight  = sidebar.height();

    slideMenu(toggle, sidebar)
});
于 2013-08-21T15:50:44.447 回答
0
 $(function() {

effectdemo("#pull",'.main-nav ul');
effectdemo('#toggle-handle','.blog-sidebar-wrap');

    });

function effectdemo(starter,sliderconatiner)
{
         var toggle        = $(starter);
            sidebar        = $(sliderconatiner);
            sidebarHeight  = sidebar.height();

        $(toggle).on('click', function(e) {
            e.preventDefault();
            sidebar.slideToggle('fast');
        });

}
于 2013-08-21T15:58:05.433 回答