简体   繁体   中英

how should you pass a context to a named function using jQuery .on?

I have a function I need to call from a few different places, the function runs after clicking an 'a' tag or from a submit event, and in all three instances I need to preventDefault but I get the error 'cannot preventDefault of undefined'.

$('a#Link').on('click', supaFunc);

function supaFunc(e) {
    e.preventDefault();

    // do all the things...

}

Had a look at the documentation but I haven't solved it. I'm sure its to do with context, and I can make this work buy calling an anonymous function in the .on method that works fine, but I'd prefer not repeat this function three times.

jQuery event handlers should always receive the event as their first argument. If it's undefined, I would suspect that you call the handler in a different fashion at some place.

To find out where and how, try changing the code to

function supaFunc(e) {
    if (typeof e === 'undefined') {
      debugger;
    }
    e.preventDefault();
}

Now, when the function is called without an argument, the debugger will kick in.

Open the developer tools of your browser and reload / run the page. When the problem occurs, follow the call stack downwards until you find the location where supaFunc was called without an event as an argument.

在此处输入图片说明

Example image of the Chrome Developer Tools debugger.

可能在所有三种情况下都不存在<a id="link"></a> ,该错误似乎表明了这一点。

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