如何命名和调用 jQuery 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7963609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:32:35  来源:igfitidea点击:

How can I name and call a jQuery function?

jquery

提问by Samantha J T Star

I have the following:

我有以下几点:

 $('#EID').change(function () {
                $.ajax({
                    url: "/Administration/stats",
                    data: { DataSource: $('#DataSource').val(),
                            EID: $('#EID').val()
                    },
                    success: function (data) {
                        $('#TID').html(data);
                    }
                });
            });

This works good but I want to be able to call the function () at other times and not just when EID changes. Can someone show me how I can pull out the function code into a separate block with a name and then call that function name.

这很好用,但我希望能够在其他时间调用函数 (),而不仅仅是在 EID 更改时调用。有人可以告诉我如何将函数代码提取到具有名称的单独块中,然后调用该函数名称。

回答by ThiefMaster

function doSomething() {
    $.ajax(...);
}

$('#EID').change(doSomething);

Note that you must notadd ()after the function name since you want to pass the function, not its return value.

请注意,您不能()在函数名称后添加,因为您要传递函数,而不是其返回值。

In case you wanted to pass some parameter to the function, you'd do it like this:

如果你想向函数传递一些参数,你可以这样做:

function doSomething(someParam) {
    $.ajax(...);
}

$('#EID').change(function() {
    doSomething(whateverSomeParamShouldBe);
});

回答by Nancy256

Well , the other thing you can do for someone looking for answer now is to trigger the function

好吧,您现在可以为正在寻找答案的人做的另一件事是触发该功能

$('#EID').change (function (){
    //your code here;
});

Some other function or code you want to call the previous unnamed function , you can simply do;

其他一些函数或代码你想调用之前的未命名函数,你可以简单地做;

$('#classOrId).eventYouwannaUse (function (){
$('#EID').change ();
 });

回答by Nancy256

Or you can use on(); function and then define the function name

或者你可以使用 on(); 函数然后定义函数名

$('#EID').on('change' , ChangeEventfuncCode);
function ChangeEventfuncCode(){
 //your code ......
}

And then call the function anywhere you want..;

然后在任何你想要的地方调用函数..;

$('.classOrId').whateverEvent(function (){


//your code......
ChangeEventfuncCode();
});