Bind Event to Custom Plugin Function in jQuery

2019-06-07 21:39发布

问题:

How would I modify my plugin to allow to load with an event on the call? Right now the plugin is loading when the page loads and I want it to work with .blur() or whatever event I want to assign it instead. Any help would be appreciated:

// 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();

It's not working on blur(), it's triggering the plugin on document load instead of the .blur() event.

回答1:

In Javascript, when you put () after a function name, it causes it to be executed immediately. So when the interpreter encounters ("[name$='_required']").required().blur();, it executes required immediately and then attaches the return value to blur() (which is not what you want, it seems). Try doing it this way:

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

That should bind the actual function object of required to blur() and cause it to be executed on that event.



回答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();
})