简体   繁体   中英

pass event object and other parameters to a JavaScript function

I know similar questions have been asked, but I couldn't find any answer. There is a JavaScript function:

function init(url) {
    $('#id_search').keyup(function() {
        performsearch(url, e);
    });
}

I am trying to pass event object and the url parameter to the performsearch function:

function performsearch(url, e){
        e.preventDefault();
        console.log('perf->' + url);
    }

But e.preventDefault() gives an error:

e is not defined

What is wrong in this function call?

You need to get the event from the keyup 's callback function.

function init(url) {
    // Get the event parameter of the callback function
    $('#id_search').keyup(function (e) {
        performsearch(url, e);
    });
}

You can do this with closure. Your problem may be solved using other solutions but you might encounter problems later on that you might need this technique.

     $('#id_search').keyup(function(url) {
         return function (evt) {
             evt.preventDefault();
             console.log('perf->' + url); 
        };

     })();

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