什么是使用jquery插件选择表单中所有输入的最佳方法

时间:2011-10-14 23:03:23

标签: jquery jquery-plugins jquery-selectors

我正在制作自己的jQuery验证插件。在插件中选择具有data-validate属性的输入字段的最佳方法是什么?为了澄清这个插件可以是sent $('form').validate() 它可能在给定页面上处理超过1个表单

新问题 所以我现在正在使用

    var options =  $.extend(defaults, options);
    return this.each(function() 
    {
    form=this;
    //lazy
    $(this).submit(function()
    {

        var o = options;
        $('['+o.attr+']', form).each(function()
        {
            var val=$(this).val()
            alert($(this).attr('name'))
        })
        //if errors
        //encapsulate error group
        //add to html with .after()
        return false;
        //no errors send
    })
    });
发生的事情是,由于某种原因,插件只能获得最后一个形式。注意我只有插件的主要功能o.attr值是data-validate有效。 这是我在http://yamikowebs.com/_test/project/

上创建的页面的链接

2 个答案:

答案 0 :(得分:2)

(function(){
    $.fn.myplugin = function(options) {
        return this.each(function(){ // <-- this part makes your function execute on every element passed to it
             $('input[data-validate]', this).each(function(){ // <-- this part iterates over all inputs with an attribute of "data-validate" in the current (", this" part) form
                 // do stuff here
             });
        });
    }
})(jQuery);

用法:

$('form').myplugin();
//  |
//  |
//   --- If multiple forms are on the page, jQuery will pass all of them to your plugin

进一步阅读:jQuery Plugin Authoring.

修改

奖金:Working Fiddle to illustrate it all

修改2

哎呀,累了的时候不应该这样。更新了答案并小心翼翼地回答OP的问题。

答案 1 :(得分:1)

$('input[data-validate]').each(function() { ... });