jquery stop executing after callback function
I have a simple plugin, used for submitting form
(function($){
$.fn.ajaxSubmit = function(options){
var defaults = {
onSubmit:function(){},
},
o = $.extend({},defaults, options);
return this.each(function(){
$(this).submit(function(e){
o.onSubmit.call(this);
$.post(o.url,$(this).serialize() ,
function(i){"do stuff"},'json');
return false;
});
});
}
})(jQuery);
开发者_运维百科
And this is how I call it
$('#commentForm').ajaxSubmit({
onSubmit:function(){
if($('textarea').val()==''){ "do not execute $.post"}
}
});
I want to check if textarea is empty, if it is, do not proceed further down the plugin or do not execute the $.post.
Building on gap's answer:
(function($){
$.fn.ajaxSubmit = function(options){
var defaults = {
shouldSubmit:function(){ return true; },
},
o = $.extend({},defaults, options);
return this.each(function(){
$(this).submit(function(e){
if(o.shouldSubmit.call(this)) {
$.post(o.url,$(this).serialize(), function(i){"do stuff"},'json');
}
return false;
});
});
}
})(jQuery);
$('#commentForm').ajaxSubmit({
onSubmit:function(){
if($('textarea').val()==''){ return false; }
}
});
Changed the function name to shouldSubmit as that makes more sense and set the default to return true so it always submits if it hasn't been overridden.
I would have the onSubmit handler return a bool, and let the plugin test that return value.
精彩评论