且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-11 03:16:34

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