1

呼び出し時にイベントをロードできるようにプラグインを変更するにはどうすればよいですか?現在、プラグインはページの読み込み時に読み込まれ、.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()イベントの代わりにドキュメントロードでプラグインをトリガーします。

4

2 に答える 2

1

Javascriptでは()、関数名の後に置くと、すぐに実行されます。したがって、インタプリタがに遭遇すると("[name$='_required']").required().blur();、すぐに実行requiredされ、戻り値がに付加されますblur()(これはあなたが望むものではないようです)。このようにしてみてください:

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

requiredこれにより、 toの実際の関数オブジェクトがバインドblur()され、そのイベントで実行されるようになります。

于 2009-12-31T01:15:25.753 に答える
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();
})
于 2009-12-31T01:43:09.877 に答える