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

如何修改我的插件以允许加载呼叫中的事件? 现在,当页面加载时,插件正在加载,我希望它与.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('err msg'); } } 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()事件上触发插件。

在Javascript中,当你在函数名之后放()时会导致它立即执行。 所以当翻译遇到("[name$='_required']").required().blur(); ,它立即执行required ,然后将返回值附加到blur() (这似乎不是你想要的)。 尝试这样做:

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

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

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