开发者

How would you call a jQuery plugin as a method?

开发者 https://www.devze.com 2023-02-21 15:43 出处:网络
For example I have this plugin code: jQuery.fn.keys = function(ob开发者_StackOverflow社区j) { var keys = [];

For example I have this plugin code:

jQuery.fn.keys = function(ob开发者_StackOverflow社区j) {
    var keys = [];
    $.each(obj,function(i,elem) {
        keys.push(i);
    });
    return keys;
};

I'd like to apply this plugin in such a way:

var a = { 'a':1,'b':23,'c':43};
var b = $.keys(a); // should return ['a','b','c']

The above code returns an error.

How would I call the jQuery plugin as a method of the jQuery object; $.key() and not $('#elem').key()?


$.fn is used when adding methods to be called on jQuery result objects. For example, creating $.fn.extend would allow you to call something like $('#some_el').extend().

To extend $ instead, use $.extend:

$.extend({
        keys: function(obj) {
                var keys = [];
                $.each(obj, function(i, elem) {
                        keys.push(i);
                });

                return keys;
        }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消