简体   繁体   中英

can we pass “e” from one function to another in javascript/jquery?

I have written one function like:

 var link = {
       login : "#log_In"
    };

    var onLogin = function(e){
       e.preventDefault();

      //login functionality
    }

    var clickMe = function(){
       onLogin();//error can not read property of undefined "e is undefined"
    }

   var onClickFunction = {
          login : clickMe
    };

Now when i click like:

$(SELECTORS.link[key]).click(onClickFunction[key]);

I tried passing e to clickMe function and send that e to onLogin() still get "e is undefined". How should i pass this "e"??

You are pointing to the handler correctly, you just need to relay the arguments.

var link = {
   login : "#log_In"
};
var onClickFunction = {
    login : clickMe
};

var onLogin = function(e){
   e.preventDefault();

  //login functionality
};

var clickMe = function(){
    // relay the arguments to the handler onLogin
   onLogin.apply(this, Array.prototype.slice.apply(arguments));
};


$(SELECTORS.link[key]).click(onClickFunction[key]);
  • convert arguments to a proper array
  • use apply to pass them to the handler onLogin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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