目前此功能有效:
$("#email_address_input").on('focusout', function(){
emailValidationCheck($(this));
});
function emailValidationCheck(e){
...
}
基本上,如果电子邮件地址输入元素被聚焦,则会运行一个匿名函数,该函数调用声明的函数emailValidationCheck
(当然,该声明的函数将电子邮件地址作为参数)输入元素)。
那个匿名函数感觉多余。它所做的只是调用声明的函数,所以在我看来应该将其删除。
因此,我尝试做的是在事件触发时直接调用声明的函数,而不是调用匿名函数,后者又调用该声明的函数。像这样(警告,它没有按预期工作):
$("#email_address_input").on('focusout', emailValidationCheck($(this)));
问题:我怎样才能让它发挥作用?或者原来的答案是最佳实践?基本上我想做的是:当 focusout
事件在指定元素上触发时,我想执行 emailValidationCheck
函数,其中传入的参数是元素所有这些事情都发生在哪里。
谢谢!
最佳答案
您不需要使用匿名函数作为事件的回调。您可以轻松地调用已定义的函数,而无需使用 ()
前体(因为包含该函数本质上会将 emailValidationCheck
的返回值传递给回调,而不是函数引用本身) 。例如:
$("#email_address_input").on('focusout', emailValidationCheck);
现在,您的 emailValidationCheck
函数将接收您在函数构造函数中定义的 e
变量中的事件。
由于该函数已绑定(bind)为回调,因此 $(this)
在其中也可用。例如:
function emailValidationCheck(e)
{
console.log( e ); // logs the event
console.log( $(this) ); // logs the jQuery object that lost focus
}
关于javascript - 使用 .on 函数运行 jQuery 声明的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28943796/