[英]How do I write a function as both an event handler and a callable function that takes an argument?
Here's a function for use as an event handler that makes use of this
: 这是一个用作事件处理程序的函数,它使用了
this
函数:
function validate() {
if (this.val() == '') {
return false;
}
}
$(':input').change(validate);
Here's the same function rewritten to take an argument, so that I can call it explicitly: 这是为了获取参数而重写的相同函数,因此我可以显式调用它:
function validate(field) {
if ($(field).val() == '') {
return false;
}
}
validate($('#customer_name'));
How can I rewrite my validate
function to make it suitable for use as both an event handler, and as a standalone function for me to call? 我怎么可以重写我的
validate
功能,使其适合用作两个事件处理程序,并作为一个独立的功能给我打电话?
There are various ways to do this. 有多种方法可以做到这一点。 One is to use the second one taking the field as a parameter and set the event handler using a closure:
一种是使用第二个将字段作为参数并使用闭包设置事件处理程序:
function validate(field) {
if ($(field).val() == '') {
return false;
}
}
// Use anonymous function to pass "this" to validate.
$(':input').change(function() { validate(this); });
// Unchanged.
validate($('#customer_name'));
Another way is to use the first form and use apply() to call it with an overridden this
: 另一种方法是使用第一种形式和使用适用()与覆盖调用它
this
:
function validate() {
if ($(this).val() == '') {
return false;
}
}
// Unchanged.
$(':input').change(validate);
// Use `$(...)` as "this" when calling validate.
validate.apply($('#customer_name'));
Use a fallback to this
if field
is not given as an argument. 使用回退来
this
,如果field
不作为参数给出。
function validate(field) {
return $(field || this).val() != '';
}
$(':input').change(validate); // using this context
validate($('#someInput')); // using a parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.