将事件绑定到 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('<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()事件。
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();
It's not working on blur(), it's triggering the plugin on document load instead of the .blur() event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Javascript 中,当您将
()
放在函数名称后面时,它会立即执行。因此,当解释器遇到("[name$='_required']").required().blur();
时,它会立即执行required
,然后附加返回值值blur()
(这似乎不是你想要的)。尝试这样做:这应该将
required
的实际函数对象绑定到blur()
并使其在该事件上执行。In Javascript, when you put
()
after a function name, it causes it to be executed immediately. So when the interpreter encounters("[name$='_required']").required().blur();
, it executesrequired
immediately and then attaches the return value toblur()
(which is not what you want, it seems). Try doing it this way:That should bind the actual function object of
required
toblur()
and cause it to be executed on that event.