2009-12-31 3 views
1

호출시 이벤트로드를 허용하도록 플러그인을 수정하려면 어떻게해야합니까? 지금은 페이지가로드 될 때 플러그인이로드되며 .blur() 또는 대신 할당 할 이벤트가 필요합니다. 어떤 도움을 주시면 감사하겠습니다 : 그것은) (흐림에 작동하지 않습니다jQuery의 사용자 정의 플러그인 기능에 이벤트 바인드

// 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() 이벤트의 문서로드에 플러그인을 트리거합니다.

답변

1

자바 스크립트에서 함수 이름 뒤에 ()을 넣으면 즉시 실행됩니다. 따라서 통역사가 ("[name$='_required']").required().blur();을 만날 때 즉시 required을 실행 한 다음 반환 값을 blur()에 연결합니다 (원하지 않는 것 같습니다). 이런 식으로 일을 시도해보십시오 blur()required의 실제 함수 객체를 결합하고이를 해당 이벤트에서 실행되도록해야

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

합니다.

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(); 
}) 
관련 문제