简体   繁体   English

如何在jQuery中调用函数?

[英]How to call a function in jquery?

I wanted to my code a bit cleaner so I wanted to put a very long function in it's own method. 我想让代码更简洁一些,所以我想在自己的方法中添加一个很长的函数。

Right now I have 现在我有

$('#Id').submit(function()
{
   // lots of code here
});

now I wanted to break it up like 现在我想把它分解

   $('#Id').submit(MyFunction);


        function MyFunction()
        {
           // code now here.
        }

but I need to pass in some parms into MyFunction. 但是我需要将一些参数传递给MyFunction。 So I tried 所以我尝试了

$('#Id').submit(MyFunction(param1, param2));

function MyFunction(param1, param2)
{
   // code now here.
}

But when I do this nothing works. 但是,当我这样做时,没有任何效果。 Firebug shows me some huge ass error about F not being defined or something. Firebug向我展示了一些有关未定义F的巨大错误。 So I am not sure what I need to do to make it work. 因此,我不确定要使其正常工作需要做什么。

You just need to write: 您只需要写:

$('#Id').submit(function()
{
   MyFunction(param1, param2);
});

You could try 你可以试试

$('#Id').submit(function() { MyFunction(param1, param2); });

The reason your code didn't work is that you were calling MyFunction(param1, param2) and passing the result to the Jquery submit - and that's not what you intended. 您的代码不起作用的原因是您正在调用 MyFunction(param1, param2)并将结果传递给Jquery submit -这不是您想要的。

You can't pass parameter directly but you can do something like this: 您不能直接传递参数,但是可以执行以下操作:

$("#Id").submit(function(){
   MyFunction(param1,param2);
});

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

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