Methods for a specific object (not prototyped)
I'd like to wr开发者_StackOverflowite a plugin that can be used in the following manner:
var img = $('#someImage').Image();
or perhaps:
var img = $.Image({id: 'someImage', src: '/...'});
and then be able to do image-related functions:
img.highlight();
img.showAlter();
et cetera. However, I don't want to do:
$.fn.highlight = function() {}
since that would apply to all jQuery objects and i want my method to apply only to those objects I've called .Image() on.
is what I'm asking for possible? how?
You'd need to place your Image
function on the prototype (fn
), but then have the Image
plugin assign the highlight
and showAfter
functions to that specific jQuery object on which .Image()
is called.
(function( $ ) {
$.fn.Image = function( props ) {
this.highlight = function(){
this.each(function() {
$(this).css('border', "5px dashed yellow");
});
};
this.showAfter = function(){};
return this;
};
})( jQuery );
var img = $('img').Image();
img.highlight();
EDIT:
To clarify, this
in the Image
function is a reference to the jQuery object against which Image()
was invoked.
this
does not reference the Image
function in any way.
Example: http://jsfiddle.net/saYLm/
$.fn.image.highlight = function() {}
assuming you have written a plugin named image this would prototype the highlight function to that object
精彩评论