JQuery plugin return value from function
Markup:
<input type="text" name="email" />
code:
$(':text').focusout(function(){
$(this).validate(function(){
$(this).attr('name');
});
});
Plugin:
(function($){
$.fn.validate = function(type) {
return this.each(function(type) {
if (type == 'email') {
matches = this.val().match('/.+@.+\..{2,7}/');
(matches != null) ? alert('valid') : alert('invalid');
}
/*else if (type == 'name') {
}
else if (type == 'age') {
}
else if (type == 'text') {
}*/
else {
alert('total failure');
}
});
};
})(jQuery);
The problem is that when the above code is executed, it launches the plugin as if the type were a string: "function () {$ (This) .attr ('name');});" instead of performing it as a function. How to solve this?
+2
source to share
1 answer
You have to check if the parameter is a function. If yes, use the return value else, let's assume it's a literal value.
(function($) {
$.fn.validate = function(type) {
//check if type type is a function else take it as literal
type = typeof type !== "function" ? type : type();
return this.each(function(type) {
...
});
};
})(jQuery);
+1
source to share