jQuery Plugin Method Chaining Class Layout
I am creating a jQuery plugin and I am having trouble setting up the class/methods to fit the api access I would like.
Here is what I have so far, but it doesn't work (I get an Object doesn't support this property or method error):
开发者_如何学运维(function( $ ){
$.kitty= function( name ) {
this.name = name;
this.cat= function( say ) {
alert( this.name + ": " + say );
}
};
})( jQuery );
I want to cause the output using:
$.kitty('chairman meow').cat('meow!');
output:
chairman meow: meow!
try
(function($) {
$.kitty = function(name) {
this.name = name;
this.cat = function(say) {
alert(name + ": " + say);
}
return this;
};
})(jQuery);
$(function() {
$.kitty('chairman meow').cat('meow!');
})
don't forget to return the object.
demo
Try this
$.kitty = function(name) {
return {
name: name,
cat: function(say) {
alert(this.name + ": " + say);
}
}
};
Your code does not work, because you are trying to call the function cat of the return value of $.kitty. Since $.kitty doesn't return anything, there is no function cat to call. It would work if you return this in $.kitty, but I don't think that is the correct way to write a jquery pluging. Take a look at this if you want to know how it works...
精彩评论