I am trying to pass a boolean parameter to a callback from inside a jquery plugin but parameter is always undefined.
The onSwitch callback parameter should alternate between true and false each time the link is clicked. Using a debugger I can see that the value passed to callback call function is properly defined as true or false but inside the callback implementation it turns to undefined.
I have tried looking at several other similar questions like this this and this but cannot seem to get this to work.
This is my plugin definition:
(function ($) {
$.fn.switcherButton = function (options) {
// Set the default options
var settings = $.extend({},$.fn.switcherButton.defaults, options);
this.click(function () {
$.fn.switcherButton.switched = !$.fn.switcherButton.switched;
settings.onSwitch.call($.fn.switcherButton.switched);
});
return this;
};
// Plugin defaults – added as a property on our plugin function.
$.fn.switcherButton.defaults = {
onSwitch: function() {}
};
$.fn.switcherButton.switched = false;
}(jQuery));
HTML:
<a id="switchTest" href="#">switch</a>
plugin initialization:
$("#switchTest").switcherButton({
onSwitch: function(switched){
if(typeof switched === "undefined")
alert("callback param = undefined");
else
if(switched)
alert("callback param = true");
else
alert("callback param = false");
}
});
I have created a jsfiddle of the problem here .
Change settings.onSwitch.call($.fn.switcherButton.switched)
to settings.onSwitch($.fn.switcherButton.switched)
Call is used to set this and not the actual argument to the function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.