如果你的函数的$(document).ready()
里面写像这样:
$(document).ready(function() {
function a() {
console.log("fun a");
}
})
那么他们只在该块内可见且不可访问它的外面。假设你的函数实际上以任何方式使用jQuery,你可以将它们作为全局jQuery函数或者jQuery方法添加到jQuery对象中。
- 将jQuery全局函数添加到
jQuery
对象本身。
- 将jQuery方法添加到
jQuery.fn
属性中。
例为两种情况:或者
$.a(); // global functions are called from the jQuery object itself
$.('.some-class').b(); // jQuery methods are called on selectors
,你可以在global object
创建一个新的对象来存储:
$(document).ready(function() {
jQuery.a = function() {
console.log("jquery global fun a");
// do something with jQuery here
}
jQuery.fn.b = function() {
console.log("jquery fun b");
// do something with jQuery here
}
})
现在你可以使用这2个功能,像这样您的应用程序的所有属性和功能。如果您计划在其中存储非jQuery代码,并且您的函数不打算作为jQuery插件发布,那么它特别有用:
window.magicApp = {}
window.magicApp.fun_a = function() {
console.log('fun a');
}
// somewhere in your code
magicApp.fun_a(); // works!
jQuery的功能?我假设你的意思是JavaScript的功能。 '所以我可以从角度调用这些函数吗?' - 你试过了吗?如果是这样,会发生什么?它会产生错误吗? – BenM
它找不到函数 – lovesh
您是否定义了'$(function(){})'(即DOMReady事件)中的函数? – BenM