开发者

write a jquery function which accepts params and object

This should be an easy one.

How to write a jquery function that gets the 'calling' object and some params.

My function code:

new function($) {
  $.fn.addcolor = function(param1, param2, param3, param4) {
    // here i would like to retrieve the 'caller' object (div.foo in this case)

  }
} (jQuery);

My code that 'calls' the function:

开发者_Python百科$('div.foo').click(function() {
  $(this).addcolor(1, 2, 3, 4);
});

I can get the params no problemo, but I want to get the content of the div.foo in the function and add some content it.


You're looking for this.

jQuery plugins in $.fn are normal methods on the $ prototype. (jQuery assigns $.fn to $.prototype)
Like any other method, you can get the context in which it was invoked using this.


In your addcolor plugin, this will represent the same jQuery object against which your plugin was called.

 // v---jQuery object
$(this).addcolor(1, 2, 3, 4);

(function($) {
  $.fn.addcolor = function(param1, param2, param3, param4) {
    // here "this" is the same object
    // this[ 0 ] to get the first DOM element
    // this.each(function(...   to iterate over the collection
  }
})(jQuery);


In jQuery plugin functions that element is referenced by this.

function($) {
  $.fn.addcolor = function(param1, param2, param3, param4) {
    // here i would like to retrieve the 'caller' object (div.foo in this case)
    var divcontent = $(this).html();
  }
} (jQuery);


this.whatever is one way...

There is also an arguments object that you can call. ie: arguments.length or arguments["parm"]


To extend jQuery I used:

(function($) {
    $.fn.extend({
        addcolor: function(param1, param2, param3, param4) {
            return this.empty().append(something);
        }
    });
})(jQuery);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜