简体   繁体   中英

How to call functions in Javascript / jquery

I have got two functions :

    function startgame() {
"some code"
    }
    function return() {
"some other code"
    }

1) how to run functions here :

$( "#start" ).on('click', function() {
    /*I need my startgame function to run when the button is clicked*/
    });

    $( "#clear" ).on('click', function(){
    /*I need my return function to run in here*/
    });

2) Second question is what is the best way to call my functions in this code :

$( "#check" ).on('click', function() {
if ( $.inArray ( newword, words ) > -1 ) { 
/*here I need to run my return function*/;
} else {
g = g+6;//adds points
/*and here I need to run my startgame function*/;
}
});

Thanks !

return is a reserved keyword. So i changed function name to return_val

JSFiddle Demo

function startgame() {
    alert("startgame");
}

function return_val() {
    alert("return");
}
$("#start").on('click', startgame);

$("#clear").on('click',return_val);
$( "#start" ).on('click', function() {
    startgame();
    });

    $( "#clear" ).on('click', function(){
    return_function()
    });

you can't call a retun as a function name , the simple answer for your question is just to call the function whenever you want using Function_Name();

If you know how to create a function, you must know how to use or call them unless you had copied them elsewhere. In JQUERY you can call function with the function name followed by () and if that function accept params then put them inside () like

$( "#start" ).on('click', function() {
     startgame();
});

$( "#clear" ).on('click', function(){
    return_function()
});

You can also do

$( "#start" ).on('click', startgame());

$( "#clear" ).on('click', return_function());

It depends on how you need them. Hope it helps!

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