简体   繁体   English

在没有触发事件的情况下调用函数

[英]Function is being called without trigger event

I have a function that I want to use in order to expand menus in various places. 我具有要在各种位置扩展菜单的功能。 I expect it to be triggered on a click of menu associated button, but at the moment it is being called on page load (I assume from within document ready), and class 'expanded' is added without clicking on a buton. 我希望可以通过单击与菜单相关的按钮来触发它,但是此刻它是在页面加载时被调用的(我认为是在文档准备就绪的情况下),并且添加了“ expanded”类,而无需单击按钮。 I am confused to why this happens, as it should be called .on('click' .. 我对为什么会发生这种情况感到困惑,因为应该将其称为.on('click' ..

jQuery(document).ready(function ($) {
    'use strict';

    $('#btn-expand-mobile-nav').on('click', showMenu('#side-navigation'));

});

function showMenu(menu) {
    var x = $(menu),
        y = 'expanded';
    if (x.hasClass(y))
        x.removeClass(y);
    else
        x.addClass(y);
}

You are calling the function immediately. 您正在立即调用该函数。 Instead defer the execution using an anonymous function: 而是使用匿名函数推迟执行:

$('#btn-expand-mobile-nav').on('click', function(){
     showMenu('#side-navigation')
});

If there were no parameters you could have done this: 如果没有参数,您可以这样做:

$('#btn-expand-mobile-nav').on('click', showMenu);

Simplistic explanation for @skobaljic : @skobaljic简单说明:

By using the function name alone, you are pointing at the variable showMenu and saying call this later as a function. 仅通过使用函数名称,就可以指向变量showMenu并说稍后将此作为函数调用。

By using function(){} you are saying, here is a temp variable, containing a function, that you can call later. 通过使用function(){}您说的是这是一个临时变量,其中包含一个函数,您以后可以调用它。

eg it is the same as: 例如,它与:

var temp = function(){
     showMenu('#side-navigation')
}
$('#btn-expand-mobile-nav').on('click', temp);  // No parenthesis on temp

As @Dave Newton rightly points out, this can be simplified using toggleClass : 正如@Dave Newton正确指出的那样,可以使用toggleClass进行简化:

$('#btn-expand-mobile-nav').on('click', function(){
     $('#side-navigation').toggleClass("expanded");
});

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

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