【问题标题】:whats the best way to select all inputs in a form with a jquery plugin使用 jquery 插件选择表单中所有输入的最佳方法是什么
【发布时间】:2011-12-08 03:16:40
【问题描述】:

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

新问题 所以我现在使用

    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/上制作的页面的链接

【问题讨论】:

    标签: jquery jquery-plugins jquery-selectors


    【解决方案1】:
    (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 的问题。

    【讨论】:

      【解决方案2】:
      $('input[data-validate]').each(function() { ... });
      

      【讨论】:

      • 不会。如果插件以表格形式发送并使用超过 1 个表格怎么办
      • 这就是each 的用途。
      • 每个都通过数据验证循环所有输入,包括页面上的其他表单。
      猜你喜欢
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 2015-07-01
      相关资源
      最近更新 更多