【问题标题】:Bind Event to Custom Plugin Function in jQuery将事件绑定到 jQuery 中的自定义插件函数
【发布时间】:2009-12-31 01:10:35
【问题描述】:

如何修改我的插件以允许加载通话中的事件?现在插件在页面加载时加载,我希望它与 .blur() 或我想分配的任何事件一起工作。任何帮助将不胜感激:

// The Plugin
(function($) {
  $.fn.required = function() {
    return this.each(function() {

      var $this = $(this), $li = $this.closest("li");
      if(!$this.val() || $this.val() == "- Select One -") {
        console.log('test');
        if (!$this.next(".validationError").length) {
          $li.addClass("errorBg");
          $this.after('<span class="validationError">err msg</span>');
        }
      } else if($this.val() && /required/.test($this.next().text()) === true) {
        $li.removeClass("errorBg");
        $this.next().remove();
      }

    });
  }
})(jQuery);

// The Event Call
$("[name$='_required']").required().blur();

它在 blur() 上不起作用,它在文档加载时触发插件而不是 .blur() 事件。

【问题讨论】:

    标签: jquery events plugins bind


    【解决方案1】:

    在 Javascript 中,当你在函数名后面加上 () 时,它会立即执行。因此,当解释器遇到("[name$='_required']").required().blur(); 时,它会立即执行required,然后将返回值附加到blur()(这似乎不是您想要的)。尝试这样做:

    $("[name$='_required']").required.blur();
    

    这应该将required 的实际函数对象绑定到blur() 并使其在该事件上执行。

    【讨论】:

      【解决方案2】:
      (function($) { 
          $.fn.required = function() { 
              var handler = function() {
                  var $this = $(this), $li = $this.closest("li"); 
                  if(!$this.val() || $this.val() == "- Select One -") { 
                    console.log('test'); 
                    if (!$this.next(".validationError").length) { 
                      $li.addClass("errorBg"); 
                      $this.after('<span class="validationError">err msg</span>'); 
                    } 
                  } else if($this.val() && /required/.test($this.next().text()) === true) { 
                    $li.removeClass("errorBg"); 
                    $this.next().remove(); 
                  } 
              };
              return this.each(function() {
                  // Attach handler to blur event for each matched element:
                  $(this).blur(handler);
              })
          } 
      })(jQuery); 
      
      // Set up plugin on $(document).ready:
      $(function() {
          $("[name$='_required']").required();
      })
      

      【讨论】:

        猜你喜欢
        • 2014-01-05
        • 2010-09-08
        • 1970-01-01
        • 2021-08-14
        • 2011-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        相关资源
        最近更新 更多