我正在编写一个jQuery插件来验证表单。该插件工作得很好,但我希望能够定义表单验证后发生的事情。所以我希望能够将函数作为参数传递。该函数将包含一堆实际提交表单的东西。验证成功后需要调用该参数。
在HTML文件中调用插件:
<script>
$(document).ready(function(){
$('#cForm').shdValidate({
success : formSubmit()
});
});
</script>
jQuery插件:
(function($) {
$.fn.shdValidate = function(options) {
//==== SETTINGS
var shdValidateSuccess = $.extend(options).success,
form = this;
//==== SUBMIT CLICK
this.children('input[type=submit]').click(function(){
//variables
var shdRequired = $(form).children('.required'),
shdValid = 0;
//validated fields
$(shdRequired).each(function(){
$(this).removeClass('shdValidateAlert');
if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); }
else { shdValid += 1; }
});
//outcome
if (shdValid == $(shdRequired).length) {
//THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW
}
return false;
});
}
}(jQuery));
如您所见,我已经评论了在插件中需要调用参数的位置。目前我无法让这个工作。
答案 0 :(得分:2)
您需要进行两项更改
$(document).ready(function(){
$('#cForm').shdValidate({
success : formSubmit
});
});
和
(function($) {
$.fn.shdValidate = function(options) {
//==== SETTINGS
var shdValidateSuccess = $.extend(options).success,
form = this;
//==== SUBMIT CLICK
this.children('input[type=submit]').click(function(){
//variables
var shdRequired = $(form).children('.required'),
shdValid = 0;
//validated fields
$(shdRequired).each(function(){
$(this).removeClass('shdValidateAlert');
if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); }
else { shdValid += 1; }
});
//outcome
if (shdValid == $(shdRequired).length) {
//THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW
if($.isFunction(shdValidateSuccess)){
shdValidateSuccess(form);
}
}
return false;
});
}
}(jQuery));