将事件绑定到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();
})