在jQuery中将事件绑定到自定义插件函数

时间:2009-12-31 01:10:36

标签: jquery events plugins bind

如何修改我的插件以允许在通话中加载事件?现在,当页面加载时,插件正在加载,我希望它与.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()事件。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

(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();
})
相关问题