将事件绑定到jQuery中的自定义插件函数 [英] Bind Event to Custom Plugin Function in jQuery

查看:171
本文介绍了将事件绑定到jQuery中的自定义插件函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改我的插件以允许在通话中加载一个事件?现在插件正在加载页面加载,我希望它与.blur()或任何事件我想要分配它。任何帮助将不胜感激:

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

它不工作于blur(),它触发了文档加载上的插件,而不是.blur )事件。

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

推荐答案

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

这篇关于将事件绑定到jQuery中的自定义插件函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆