【问题标题】:jQuery validation plugin - pass function as parameterjQuery 验证插件 - 将函数作为参数传递
【发布时间】:2013-07-25 12:26:20
【问题描述】:

我正在编写一个 jQuery 插件来验证表单。该插件效果很好,但我希望能够定义表单验证后会发生什么。所以我希望能够将函数作为参数传递。该函数将包含一堆实际提交表单的东西。验证成功时需要调用该参数。

在 HTML 文件中调用的插件:

<script>
  $(document).ready(function(){
    $('#cForm').shdValidate({
      success : formSubmit()
    });
  });
</script>

jQuery 插件:

(function($) {
  $.fn.shdValidate = function(options) {

    //==== SETTINGS
    var shdValidateSuccess = $.extend(options).success,
        form = this;

    //==== SUBMIT CLICK
    this.children('input[type=submit]').click(function(){
      //variables
      var shdRequired = $(form).children('.required'),
          shdValid = 0;

      //validated fields
      $(shdRequired).each(function(){
        $(this).removeClass('shdValidateAlert');
        if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); }
        else { shdValid += 1; }
      });

      //outcome
      if (shdValid == $(shdRequired).length) { 
        //THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW
      }
      return false;
    });

  }
}(jQuery));

如您所见,我已经注释了需要在插件中调用参数的位置。目前我无法正常工作。

【问题讨论】:

    标签: jquery html plugins


    【解决方案1】:

    你需要做两处改变

      $(document).ready(function(){
        $('#cForm').shdValidate({
          success : formSubmit
        });
      });
    

    (function($) {
      $.fn.shdValidate = function(options) {
    
        //==== SETTINGS
        var shdValidateSuccess = $.extend(options).success,
            form = this;
    
        //==== SUBMIT CLICK
        this.children('input[type=submit]').click(function(){
          //variables
          var shdRequired = $(form).children('.required'),
              shdValid = 0;
    
          //validated fields
          $(shdRequired).each(function(){
            $(this).removeClass('shdValidateAlert');
            if ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $(this).addClass('shdValidateAlert'); }
            else { shdValid += 1; }
          });
    
          //outcome
          if (shdValid == $(shdRequired).length) { 
            //THE SUCCESS PARAMETER NEEDS TO BE CALLED HERE SOMEHOW
            if($.isFunction(shdValidateSuccess)){
                shdValidateSuccess(form);
            }
          }
          return false;
        });
    
      }
    }(jQuery));
    

    【讨论】:

    • 啊啊啊啊啊啊啊。像魅力一样工作,干杯哥们。 6 分钟后会出现一个滴答声。
    猜你喜欢
    • 2013-01-27
    • 2018-09-28
    • 1970-01-01
    • 2021-04-13
    • 2022-12-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多