更有效地编写我的jQuery

时间:2013-08-21 15:47:55

标签: javascript jquery

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

//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初学者在这里!

2 个答案:

答案 0 :(得分: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)
});

答案 1 :(得分: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');
        });

}