[英]JS Jquery Namespace Calling Functions
好的標題很糟糕,但我想不出另一個描述。
我有以下代碼:
jQuery( document ).ready( function( $ )
{
$.myNamespace = {
init: function()
{
$('.button').click(function() {
this.anotherFunction();
});
},
anotherFunction: function()
{
alert('insidefunction');
}
}
$.myNamespace.init();
});
如您所見,我正在嘗試從init內調用anotherFunction,並有兩種嘗試的方法,但是沒有用。 那么我該如何調用該函數,或者我的概念有誤?
jQuery( document ).ready( function( $ )
{
$.myNamespace = {
init: function()
{
var a=this;
$('.button').click(function() {
a.anotherFunction();
});
},
anotherFunction: function()
{
alert('insidefunction');
}
}
$.myNamespace.init();
});
單擊處理程序內調用絕對是變化的東西,因為this
任何jQuery的事件處理中被設定為導致該事件的元素。
相反,請嘗試使用以下模式:
jQuery(document).ready(function($) {
$.myNamespace = (function() {
function init() {
$('.button').click(function() {
anotherFunction();
});
}
function anotherFunction() {
alert('insidefunction');
}
// return an object with all the functions you want
// available publically as properties. Don't include
// any "private" functions.
return {
init: init,
anotherFunction: anotherFunction
};
})();
$.myNamespace.init();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.