如果你的函數的$(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