开发者

How do I add a function to a specific element type in jQuery?

I can do this

jQuery.fn.validate = function(options) {
    var defaults = {
        validateOPtions1 : '',
        validateOPtions2 : ''
    };

    var s开发者_开发知识库ettings = $.extend({}, defaults, options);

    return this.each(function() {
        // you validation code goes here
    });
};

but that will make validate() available for every element. I could do this to any element: $('some selector').validate().

Is there a way I can make this only available to, say, form elements? eg. $('.mySpecialFormClass').validate()?


You'd have to have the function throw an exception if you really don't want it to work for anything but a <form> tag.

jQuery.fn.formsOnly = function() {
  return this.each(function() {
    if (!$(this).is('form')) throw "Forms only!";
    // whatever
  });
};


The answer is simple:

$('form').validate();

Selectors work a bit like this in jQuery (just as in CSS)

$('elementType.className')

See this page for more details on selectors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜