简体   繁体   English

如何在Javascript / jquery中调用函数

[英]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 : 1)如何在这里运行功能:

$( "#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 : 2)第二个问题是在此代码中调用函数的最佳方法是什么:

$( "#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. return是保留关键字。 So i changed function name to return_val 所以我将函数名称更改为return_val

JSFiddle Demo JSFiddle演示

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(); 您不能将retun作为函数名称调用,对您问题的简单答案就是只要您想使用Function_Name();可以调用该函数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 JQUERY您可以在函数名称后接()来调用函数,如果该函数接受参数,则将它们放在()例如

$( "#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! 希望能帮助到你!

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

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