jQuery 全局jquery函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6960448/
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-26 21:36:51  来源:igfitidea点击:

global jquery function

jquery

提问by haripds

I have to write global function in js file that is loaded initially. I want to write function on it so that it can be accessed from all pages. I am new in jquery. I want to know how to write function in js file and call it form other pages?

我必须在最初加载的 js 文件中编写全局函数。我想在其上编写函数,以便可以从所有页面访问它。我是 jquery 的新手。我想知道如何在js文件中编写函数并从其他页面调用它?

回答by Kyle

You can add your own jQuery function by doing the following

您可以通过执行以下操作来添加您自己的 jQuery 函数

$.fn.MyFunction = function()
{
//Code here
}

Then inside of another script or the same script, you can run your function by doing $('#myId').MyFunction();. This is for running the function on an object. The suggestion below is for just running a function.

然后在另一个脚本或同一个脚本中,您可以通过执行$('#myId').MyFunction();. 这是为了在对象上运行函数。以下建议仅用于运行函数。

Adding it to the jQuery object itself:

将它添加到 jQuery 对象本身:

$.MyFunction = function()
{
//Code here
}

Then call it as $.MyFunction()

然后称之为 $.MyFunction()

回答by ShankarSangoli

You can define the functions in js file and just include these js files in the pages where you want to use it using script tag.

您可以在 js 文件中定义函数,然后使用 script 标签将这些 js 文件包含在要使用它的页面中。

All the functions defined in the js files will become global and can be used anywhere on the page or in other js files.

js文件中定义的所有函数都将成为全局的,可以在页面的任何地方或其他js文件中使用。

<script src="scriptFileName1.js"  type="text/javascript"></script>
<script src="scriptFileName2.js"  type="text/javascript"></script>