2011-08-24 70 views
0

我試圖寫一個簡單的jQuery插件,做我需要在一個單一的元素傳遞,如$(「格」)的following-- applyPlugin()。然後讓它通過我傳入的每個選擇器,並設置一個間隔,該間隔對於該div的這個實例是本地的,然後稍後再清除它。我正在嘗試編寫一個插件來幫助完成這一任務,但似乎有一個範圍問題,我不知道發生了什麼。jQuery插件/設置間隔時間和範圍界定問題

同樣,我需要設置在一個div一個計時器,並能夠重新使用它像一個頁面上10倍。所有div本質上都會有自己的'定時器',當你重新將鼠標移到div上時,它會清除該定時器本身。鼠標關閉,重啓定時器等

我不確定這是否有權使用內部方法插件來實現,或者,如果那裏有做這更好/更簡單的方法。

這是我在迄今爲止與這 - 「

(function($){ 

var methods = { 
    init : function(options) { 
     /* init method */ 
     return setInterval($(this).boxit('update'),5000); 
    }, 
    show : function() { }, 
    hide : function() { }, 
    update : function(content) { 
     /* update method */ 
     console.log("ping"); 
    } 
}; 

$.fn.boxit = function(method) { 
    // Method calling logic 
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.tooltip'); 
    }   
}; 

})(jQuery); 

回答

0

我在這裏可以去完全錯誤的方向所以請原諒我,如果這是不是你想要的地方,但是您可以將引用傳遞給jQuery對象作爲參數。

(function($){ 

var methods = { 
    init : function(jqObject, options) { 
     /* init method */ 
     return setInterval(jqObject.boxit('update'),5000); 
    }, 
    show : function() { }, 
    hide : function() { }, 
    update : function(content) { 
     /* update method */ 
     console.log("ping"); 
    } 
}; 

$.fn.boxit = function(method) { 
    var args = Array.prototype.slice.call(arguments, 0); 
    args.splice(0, 0, $(this)); 

    // Method calling logic 
    if (methods[method]) { 
     return methods[ method ].apply(this, args.slice(1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, args); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.tooltip'); 
    }   
}; 

})(jQuery);