我想做这样的事情:
$('.dynamicHtmlForm').validate = function() { return true; } $('.dynamicHtmlForm .saveButton').click(function() { if (!$(this).closest('.dynamicHtmlForm').validate()) { return false; } return true; });
然后当我有一个类dynamicHtmlForm时,我希望能够提供一个自定义的validate()函数:
$('#myDynamicHtmlForm').validate = function() { // do some validation if (there are errors) { return false; } return true; }
但是当我这样做时,我得到了这个:
$(this).closest(".dynamicHtmlForm").validate is not a function
我所描述的甚至可能吗?如果是这样,我做错了什么?
解决方法
jQuery.fn.validate = function(options) { var defaults = { validateOPtions1 : '',validateOPtions2 : '' }; var settings = $.extend({},defaults,options); return this.each(function() { // you validation code goes here }); }; $(document).ready(function() { $('selector').click(function() { $('some selector').validate(); // or if you used any options in your code that you // want the user to enter. then you go : $('some selector').validate({ validateOPtions1: 'value1',validateOPtions2: 'value2' }); }); });