Jquery plugin problem. How do I return a value?
I wrote a simple jquery validation plugin for learning puposes, and it works fine. But I am new to this, and have no idea how to return a value from the plugin.
(function($){
$.fn.bluevalidate = function(options){
var defaults = {
errorMsg : 'You have an error',
required : false,
no_space : false,
no_special_chars : false,
numbersOnly : false,
max_chars : 0,
min_chars : 0,
matchWith : '',
matchMsg : 'Please retype the same value',
email : false
};
var opt = $.extend(defaults,options);
r开发者_开发问答eturn this.each(function(index,element){
var e = $(element);
var p = e.parents('span:eq(0)');
var msg = [];
e.focus(function(){
msg = [];
});
//-------------------------------------------------------------------------------
//Handle required
if(opt.required==true)
{
e.blur(function(evt){
if(e.val()=='')
{
e.css('background','#ffcccc');
msg.push('This field is required.');
}
else
{
e.css('background','#ffffff');
}
displayMsg();
});
}
....
....
..
basically I need to find out the number of errors on the form. So I thought I would write a function to trigger the blur() event on all fields and thus get the errors. But how do I return this value to a variable outside the plugin?
if possible, can someone give me a short example code to show how to return a value, and if there are any better alternatives to the situation?
Since each jQuery plugin should return a wrapped set of jQuery objects (to keep the chain alive), you can't (well, actually you could, but you shouldn't) return any value by using return;
.
Since you correctly returning the jQuery wrapped set, you can invoke a callback function to deal with a value which you actually would return. Your options object is a perfect place for that:
$('element').bluevalidate({
/* some flags */
callback: function(value) {
// do something with value
}
});
You can invoke that callback at any point within your plugin function. Let's assume you want to do something with your variable p
, it would look like:
if( typeof options.callback === 'function' )
options.callback.apply(this, [p]);
This would call your callback-function and passes the variable. The this
is actually not necesarry but it's a nice bonus to have the current node as context aswell within your callback.
精彩评论