2010-04-14 72 views
6

我想要做这样的事情:如何通过jQuery为元素添加一个函数?

$('.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 

是我所描述的甚至可能吗?如果是这样,我做错了什么?

回答

3
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' 
     }); 

    }); 

}); 
3

您不是将函数添加到元素,而是将它添加到元素周围的jQuery包装器中。如果您保存包裹元素给一个变量和使用以后,这将是一个不同的故事,因为你”

$('#myEl'); // gives a jQuery wrapper object 
$('#myEl'); // creates another jQuery wrapper object 

:每一次你通过一个选择器,jQuery的时候,它会为找到的元素的新包装重新访问保存的jQuery包装器对象。

var dynamicHtmlForm = $('.dynamicHtmlForm'); 
dynamicHtmlForm.validate = function() { 
    return true; 
} 

$('.dynamicHtmlForm .saveButton').click(function() { 
    if (dynamicHtmlForm.validate()) { 
    return false; 
    } 

    return true; 
} 

你也可以直接添加的功能使用

$('.dynamicHtmlForm')[0].validate = function() { return true; } 

// and later... 
if (!$(this).closest('.dynamicHtmlForm')[0].validate()) 

元素或者你可以看看由writing a plugin适当延长jQuery的。

5

是的,这在技术上是可行的。但是,您需要引用元素本身,而不是jQuery集合。这应该工作:

$('.dynamicHtmlForm').each(function (ix,o) { 
    o.validate = function() { 
    return true; 
    } 
}); 

$('.dynamicHtmlForm .saveButton').click(function() { 
    if ($(this).closest('.dynamicHtmlForm')[0].validate()) { 
    return false; 
    } 

    return true; 
} 
相关问题