Answer the question
In order to leave comments, you need to log in
How to implement click function in jQuery plugin?
Friends, I'm racking my brains for the second day. I can't figure out how to make the click event handler work:
<div id='block'></div>
<script>
(function( $ ){
var defaults = {fullstar:'icon-star-1', emptystar:'icon-star-two', halfstar:'icon-star-half', click: function() { } };
var methods = {
init : function( options ) {
return this.each(function() {
this.config = $.extend({}, defaults, options);
}),
click : function(content) {
return this.each(function() {
alert(999);
})
};
$.fn.myFunc = function( method ) {
// Метод вызывающий логику
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 + ' не существует в jQuery.tooltip' );
}
};
})( jQuery );
$('div#block').myFunc({'halfstar':'icon-star-half', click: function(){ alert(888); } });
</script>
Answer the question
In order to leave comments, you need to log in
I will not say anything about the absence of a pair of curly braces and about the meaning of such code. I'll just describe what's going on. Your myFunc method takes a method variable, and as you understand from your code, you expect method to be a string, then you yourself pass the object {'halfstar':'icon-star-half', click: function(){ alert(888); } }, now method is an object and hence the condition (very strange btw) typeof method === 'object' || ! method - will be true and the code will be executed: return methods.init.apply( this, arguments ) - this code writes the config property to the GLOBAL object with the value $.extend({}, defaults, options). Question to you, which click should work?
upd sorry for the global configuration in the same place each jquery context will be correct
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question